Swag: Dynamic Host IP

Created on 1 Apr 2019  路  7Comments  路  Source: swaggo/swag

Is their any way to dynamically assigning Host IP in swagger.yaml. Issue is if same swagger file is to be run on different hosts than their respective IP's have to be manually defined.
Need a way so that swagger can dynamically get Host IP.

question

Most helpful comment

@chiragg6 I found a solution:
if you use doc.json as the spec source, there is a hook in docs/doc.go(generated by swag init)
do not add host annotation, then the generated spec will leave a placeholder:

{
    "host": "{{.Host}}"
}

setup you dynamic host ip, before serve the swagger ui.

import (
        "path/to/your/project/docs"
)

func init() {
        // this host will fill the placeholder.
        docs.SwaggerInfo.Host = "your dynamic host"
}

All 7 comments

Swag don't support this case yet. I can't thought for this case.

How do you want to?
I thought this.
eg: swag init --host "localhost:8080"

@chiragg6 I found a solution:
if you use doc.json as the spec source, there is a hook in docs/doc.go(generated by swag init)
do not add host annotation, then the generated spec will leave a placeholder:

{
    "host": "{{.Host}}"
}

setup you dynamic host ip, before serve the swagger ui.

import (
        "path/to/your/project/docs"
)

func init() {
        // this host will fill the placeholder.
        docs.SwaggerInfo.Host = "your dynamic host"
}

I see.
Can you write this solution in README.md?
@webee

@pei0804
actually, this solution is in https://github.com/swaggo/swag#how-to-use-it-with-gin

        // programatically set swagger info
        // do not add corresponding declaritive comment to enable it
    docs.SwaggerInfo.Title = "Swagger Example API"
    docs.SwaggerInfo.Description = "This is a sample server Petstore server."
    docs.SwaggerInfo.Version = "1.0"
    docs.SwaggerInfo.Host = "petstore.swagger.io"
    docs.SwaggerInfo.BasePath = "/v2"

it just need to point out that do not add corresponding annotation.

@pei0804 @chiragg6
another solution:
you can start a standalone swagger-ui service(use docker, whatever) or just use https://petstore.swagger.io/
then you serve the swagger.json file, you can modify it anyway.
eg, use echo:

    e.GET("/docs/swagger.json", func(c echo.Context) error {
        f, err := os.Open(docFile)
        if err != nil {
            return err
        }
        defer f.Close()

        dec := json.NewDecoder(f)
        data := make(map[string]interface{}, 0)
        if err := dec.Decode(&data); err != nil {
            return err
        }
        data["host"] = host
        return c.JSON(http.StatusOK, data)
    })

then open https://petstore.swagger.io?url=http://you/swagger.json

Was this page helpful?
0 / 5 - 0 ratings

Related issues

koddr picture koddr  路  3Comments

touyu picture touyu  路  3Comments

JimChung0403 picture JimChung0403  路  3Comments

LennyPenny picture LennyPenny  路  4Comments

dz0ny picture dz0ny  路  5Comments