1

I have an application written in Go that exposes a REST APIs. I'm trying add swagger documentation for the API. The idea is to serve the swagger spec when the user tries to hit /api-docs and display swagger UI/redoc UI when they hit /swaggerui. The swagger spec (.json) file is pregenerated and is part of the codebase. To expose the swagger spec, I tried to read the swagger spec using ioUitl.ReadFile and http.ServeFile. This works fine when it is run from IDE or the current directory but if I build the app to create the executable and copy the executable to another location it doesn't work; it looks like it is looking to read from the file system and not from within the executable. I come from java background and loading a resource bundled within web application could be easily achieved. I'm new to golang and need help on how to bundle a json file as part of executable and read/serve the json when an API request is received.

Examples I tried:-

func serveswagger(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadFile("api/api-docs/swagger.json")
if err != nil {
    fmt.Print(err)
}
w.Write(b)

}

func pastaWorkspacePage(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "api/api-docs/swagger.json")
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
user1573133
  • 904
  • 1
  • 9
  • 23

0 Answers0