Skip to content

Getting started

Install

go get gitlab.com/phpboyscout/go/transport-openapi

Mount the docs

Register takes your mux and your OpenAPI document (as bytes) and mounts two routes onto the mux:

package main

import (
    "net/http"
    "os"

    openapi "gitlab.com/phpboyscout/go/transport-openapi"
)

func main() {
    mux := http.NewServeMux()

    // Your API…
    mux.HandleFunc("GET /v1/hello", func(w http.ResponseWriter, _ *http.Request) {
        _, _ = w.Write([]byte(`{"message":"hi"}`))
    })

    // Your generated OpenAPI document (embed it, read it, or generate it).
    spec, _ := os.ReadFile("openapi.yaml")

    if err := openapi.Register(mux, spec); err != nil {
        panic(err)
    }

    _ = http.ListenAndServe(":8080", mux)
}

Run it and open the routes:

Route Serves
GET /openapi.yaml your spec bytes (Content-Type: application/yaml)
GET /docs/ the Stoplight Elements UI — an interactive reference with a try-it console
GET /docs/{asset} the embedded UI JS/CSS
curl -s localhost:8080/openapi.yaml | head
open http://localhost:8080/docs/

Because the spec and the UI are served by the same server as your API, the "try it" console calls your live endpoints same-origin — no CORS configuration needed.

Embed the spec

In a real build you will usually embed the generated spec rather than read it at runtime:

import _ "embed"

//go:embed openapi.yaml
var spec []byte

// …
openapi.Register(mux, spec)

Next