Getting started¶
Install¶
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 |
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:
Next¶
- Customise the spec and docs paths (e.g. version them
under
/v1/). - Configure security headers.
- Serve on a go/transport server alongside the rest of your stack.