Home  >  Article  >  Backend Development  >  Unable to load API definition using go-openapi/runtime/middleware

Unable to load API definition using go-openapi/runtime/middleware

王林
王林forward
2024-02-13 21:00:221097browse

无法使用 go-openapi/runtime/middleware 加载 API 定义

# During the development process, editor Banana sometimes encounters a problem: the API definition cannot be loaded using go-openapi/runtime/middleware. This problem may affect the normal progress of the project, so it needs to be solved in time. Before solving this problem, we need to understand what go-openapi/runtime/middleware is and why the API definition cannot be loaded. In this article, we will explain the cause of this problem in detail and provide solutions to help everyone solve this problem smoothly.

Question content

I am using golang's http/net and github.com/go-openapi/runtime/middleware to explore## swagger in #go. Use 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 visit

http://localhost:8088/docs I get the following:

At first glance, the

net/http library as well as middleware cannot find the swagger.json file relative to the server root. I have the file located at:

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, when testing a cloned project before deploying it, how do I tell

middleware where to find swagger.json in the current directory?

Solution

Looking from the source code, you need to do the following:

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

If specurl is not specified, the default is:

/swagger.json

The above is the detailed content of Unable to load API definition using go-openapi/runtime/middleware. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete