# README
What it is?
This package implements:
- creation of instrumented http.Server
- offer ready implementations for /status and /api-docs endpoints
How to use it?
-
Create openapi.yaml file with desired endpoints
-
Ensure you add mandatory common /status and /api-docs endpoints
/status: get: summary: Docker probe for readiness responses: "200": description: successful operation /api-docs: get: summary: Swagger documentation endpoint responses: "200": description: successful operation
-
Code generate out of swagger
make oapi-gen
By end of it you should have "api" package generated.
-
Create "endpoints" package
-
Create serverimpl.go to host your swagger endpoints handing
type ServerImpl struct { log logging.Logger swaggerJSON []byte } // New instantiates new ServerInterface implementation func New(log logging.Logger) (*ServerImpl, error) { var err error s := ServerImpl{ log: log, } s.swaggerJSON, err = httpmiddleware.GetSwaggerJSON(api.GetSwagger) return &s, err } // GetApiDocs serves Swagger documentation endpoint (GET /api-docs) // nolint:golint,stylecheck func (s *ServerImpl) GetApiDocs(w http.ResponseWriter, r *http.Request) { httpmiddleware.GetApiDocs(w, r, s.swaggerJSON, s.log) } // GetStatus implements /status // nolint:golint,stylecheck func (s *ServerImpl) GetStatus(w http.ResponseWriter, r *http.Request) { httpmiddleware.GetStatus(w, r) }
-
In your main.go use it like following
// HTTPServer is abstracting needed http.Server methods type HTTPServer interface { ListenAndServe() error Shutdown(ctx context.Context) error } func newHTTPServer(config *EnvConfig, si api.ServerInterface) (HTTPServer, error) { httpMiddleware, err := httpmiddleware.New(api.Handler(si), api.GetSwagger) if err != nil { return nil, fmt.Errorf("failed creating http middleware: %s", err) } server := http.Server{ Addr: fmt.Sprintf("%s:%d", config.Addr, config.Port), Handler: httpMiddleware, } return &server, nil }
# Functions
GetApiDocs serves /api-docs nolint:golint,stylecheck.
GetApiDocsV2 serves /api-docs nolint.
GetStatus serves /status.
GetSwaggerJSON returns swagger as bytes, used in GetApiDocs.
GetUserNameFromRequestToken retrieves the userName from the http Authorization header.
GetUserNameFromRequestTokenOrElse returns user name from Authorization token or elseName if no such exists.
InstrumentHTTPHandlerWithTracing adds basic tracing middlewares to handler.
New is instantiating new HTTP handler instrumented with common functionality si is in fact "api.Handler(si)" (call to the function generated by swagger code generator) gsFnc is in fact "api.GetSwagger" (the function generated by swagger code generator) See README.md how to use it.
NewWithValidationOptions enables passing options for the request validation.
# Type aliases
GetSwaggerFnc is in fact api.GetSwaggerFnc.