Home > Software engineering >  Failed to load API definition with go-openapi/runtime/middleware
Failed to load API definition with go-openapi/runtime/middleware

Time:12-02

I am using golang's http/net along with github.com/go-openapi/runtime/middleware to explore Swagger within go. Using the following code:

  func setupAndRunHTTPServer() {
    httpPort := envString("HTTP_PORT", defaultHTTPPort)
    httpAddr := net.JoinHostPort("localhost", httpPort)
    service := planting.NewPlantingService()
    eps := endpoints.NewEndpointSet(*service)
    httpServerMux := transport.NewHTTPHandler(eps)

    // Setup the swagger docs and UI.
    var sh http.Handler = middleware.SwaggerUI(middleware.SwaggerUIOpts{}, nil)
    httpServerMux.Handle("/docs", sh)

    // The HTTP listener mounts the Go kit HTTP handler we created.
    httpListener, err := net.Listen("tcp", httpAddr)
    if err != nil {
      os.Exit(1)
    }

    // Serve using the net/http.ServerMux creaded in transport package.
    err = http.Serve(httpListener, httpServerMux)
    if err != nil {
      os.Exit(2)
    }
    defer httpListener.Close()
  }

When I go to http://localhost:8088/docs I get the following:

enter image description here

At first glance it appears to me that the net/http library along with the middleware cannot find the swagger.json file relative to the server root. I have that file located in:

matthew.hoggan in ~/go/src/project/root on TemplateServer*
⚡ ls -l ./docs/swagger.json
-rw-r--r--  1 matthew.hoggan  staff  3880 Nov 30 04:47 ./docs/swagger.json

My question is, how do I tell the middleware, where to find the swagger.json situated in the current directory while testing the cloned project prior to deploying it?

CodePudding user response:

from the source code it appears you need to do the following:

var sh http.Handler = middleware.SwaggerUI(middleware.SwaggerUIOpts{SpecURL: "./docs/swagger.json"}, nil)

If SpecUrl is not specified it will default to: /swagger.json

  • Related