swaggo / swag

Automatically generate RESTful API documentation with Swagger 2.0 for Go.
MIT License
10.51k stars 1.19k forks source link

swag init generates empty paths/routes with v1.8.3 onwards #1622

Open owais1412 opened 1 year ago

owais1412 commented 1 year ago

Describe the bug Not able to generate swagger files for my project. Tried swag init --parseDependency -g main.go as well. Still the same. Only these lines are outputted in the console.

create docs.go at docs/docs.go
create swagger.json at docs/swagger.json
create swagger.yaml at docs/swagger.yaml

It works fine with version v1.8.2 and below.

Your swag version swag v1.8.3 and onwards

Your go version Go 1.19.3

AxelRHD commented 1 year ago

Same problem here.

Project structure:

project |-- cmd | |-- server | |-- main.go |-- server |-- server.go

main function is importing a StartServer function from the server package, where the router is settled.

The question is: how swaggo is parsing the server endpoints?

sdghchj commented 1 year ago

Same problem here.

Project structure:

project |-- cmd | |-- server | |-- main.go |-- server |-- server.go

main function is importing a StartServer function from the server package, where the router is settled.

The question is: how swaggo is parsing the server endpoints?

swag init -g ./cmd/main.go -d ./server
AxelRHD commented 1 year ago

Same problem here. Project structure: project |-- cmd | |-- server | |-- main.go |-- server |-- server.go main function is importing a StartServer function from the server package, where the router is settled. The question is: how swaggo is parsing the server endpoints?

swag init -g ./cmd/main.go -d ./server

That doesn't work either swag init -g ./cmd/server/main.go -d ./server

Got this error:

2023/07/17 21:03:17 Generate swagger docs....
2023/07/17 21:03:17 Generate general API Info, search dir:./server
2023/07/17 21:03:17 cannot parse source files /home/axelr/go-projects/swagger-chi-playground/server/cmd/server/main.go: open /home/axelr/go-projects/swagger-chi-playground/server/cmd/server/main.go: no such file or directory

The resolution of the folder structure is incorrect.

panzouh commented 1 year ago

Same issue here, project structure :

├── README.md
├── controllers
│   ├── bozo-coin.go
│   ├── controller.go
│   ├── default-route.go
│   └── user.go
├── docs
│   ├── docs.go
│   ├── swagger.json
│   └── swagger.yaml
├── go.mod
├── go.sum
├── license
├── main.go
├── metrics
│   ├── bozo-coin.go
│   └── metrics.go
├── models
│   ├── bozo-coin.go
│   ├── models.go
│   └── user.go
└── utils
    ├── db-connection.go
    ├── error.go
    └── message.go

Go version : 1.18.10 (also tried in 1.20.1 and 1.17.10) Swag version 1.8.10

Output json :

{
    "swagger": "2.0",
    "info": {
        "description": "A Bozo coin management service API in Go using Gin framework, storing data in PostgreSQL and using Prometheus for metrics.",
        "title": "Bozo API",
        "contact": {
            "name": "Bozo Support",
            "url": "https://danstonkube.fr",
            "email": "contact@danstonkube.fr"
        },
        "license": {
            "name": "Apache 2.0",
            "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
        },
        "version": "1.0"
    },
    "basePath": "/api/v1",
    "paths": {}
}

Obtained by running :

swag init --pd -g main.go
d-honeybadger commented 1 year ago

In my case empty paths were due to runtime.GOROOT() producting an empty string (and, I believe, since swag ignores all paths with runtime.GOROOT() prefix, it ignored all of them). The reason runtime.GOROOT() would be empty could be b/c of the way swag is built. In my case it was a nix package, with this issue: https://github.com/NixOS/nixpkgs/issues/224701

panzouh commented 1 year ago

I am adding more context b/c it could be related :

❯  swag init --pd
2023/07/27 14:22:36 Generate swagger docs....
2023/07/27 14:22:36 Generate general API Info, search dir:./
2023/07/27 14:22:38 warning: failed to evaluate const locb at /Users/panz/go/1.18.10/pkg/mod/github.com/pelletier/go-toml/v2@v2.0.8/internal/characters/utf8.go:183:2, strconv.ParseUint: parsing "b10000000": invalid syntax
2023/07/27 14:22:38 warning: failed to evaluate const hicb at /Users/panz/go/1.18.10/pkg/mod/github.com/pelletier/go-toml/v2@v2.0.8/internal/characters/utf8.go:184:2, strconv.ParseUint: parsing "b10111111": invalid syntax
2023/07/27 14:22:40 create docs.go at docs/docs.go
2023/07/27 14:22:40 create swagger.json at docs/swagger.json
2023/07/27 14:22:40 create swagger.yaml at docs/swagger.yaml

Issue on this repo

In my case empty paths were due to runtime.GOROOT() producting an empty string (and, I believe, since swag ignores all paths with runtime.GOROOT() prefix, it ignored all of them). The reason runtime.GOROOT() would be empty could be b/c of the way swag is built. In my case it was a nix package, with this issue: NixOS/nixpkgs#224701

package main

import (
    "flag"
    "fmt"
    "log"
    "net/http"
    "runtime"

    swaggerFiles "github.com/swaggo/files"
    ginSwagger "github.com/swaggo/gin-swagger"
    "gitlab.com/panzouh/bozo-api/controllers"
    "gitlab.com/panzouh/bozo-api/docs"
)

func main() {
    address := flag.String("address", ":", "address to listen on")
    port := flag.String("port", "3000", "port to listen on")
    // Truncated
    appRouter := gin.Default()
    // programmatically set swagger info
    docs.SwaggerInfo.Title = "Bozo API"
    docs.SwaggerInfo.Description = "A REST API for the Bozo app using Gin and GORM, PostgreSQL, and Prometheus."
    docs.SwaggerInfo.Version = "1.0"
    docs.SwaggerInfo.Host = *address + *port
    docs.SwaggerInfo.BasePath = "/api/v1"

    // Truncated
    // Set swagger route
    appRouter.GET("/docs/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

    //fmt Print runtime goroot
    fmt.Println(runtime.GOROOT())

    // Truncated
    // Run the app server
    err := appRouter.Run(*address + *port)
    if err != nil {
        panic(err)
    }
}
❯ go run main.go
/Users/panz/.goenv/versions/1.18.10
owais1412 commented 1 year ago

Any updates?

blcpeck commented 1 year ago

I have this issue as well, the paths block is empty, even though I've added a section to (minimally) describe it:

// handleNewToken godoc // @Summary Create New Token // @ID new-token // @Accept json // @Produce json // @Success 200 // @Failure 404 // @Router /newToken [post] func handleNewToken(s *Server) http.HandlerFunc {

The title and version info are created in the generated swagger.json, but the paths entry is empty. My GoRoot is set (/usr/local/go) and this application is not in that path, so it should not be skipped.

I do also get the invalid syntax that I see some other folks posting when I run with --pd:

swag init --pd 2023/08/09 12:18:21 Generate swagger docs.... 2023/08/09 12:18:21 Generate general API Info, search dir:./ 2023/08/09 12:18:22 warning: failed to evaluate const locb at /home/abc/gocode/pkg/mod/github.com/pelletier/go-toml/v2@v2.0.6/internal/characters/utf8.go:183:2, strconv.ParseUint: parsing "b10000000": invalid syntax 2023/08/09 12:18:22 warning: failed to evaluate const hicb at /home/abc/gocode/pkg/mod/github.com/pelletier/go-toml/v2@v2.0.6/internal/characters/utf8.go:184:2, strconv.ParseUint: parsing "b10111111": invalid syntax 2023/08/09 12:18:22 create docs.go at docs/docs.go 2023/08/09 12:18:22 create swagger.json at docs/swagger.json 2023/08/09 12:18:22 create swagger.yaml at docs/swagger.yaml

panzouh commented 1 year ago

Posting an update since I somehow figured how to generate documentation, it seems that including my controller directory and persist dependencies affected swag's behavior :

❯ swag init -g main.go --pd -d ./,./controllers
2023/08/17 14:36:38 Generate swagger docs....
2023/08/17 14:36:38 Generate general API Info, search dir:./
2023/08/17 14:36:38 Generate general API Info, search dir:./controllers
2023/08/17 14:36:40 warning: failed to evaluate const locb at /Users/panz/go/1.20.1/pkg/mod/github.com/pelletier/go-toml/v2@v2.0.8/internal/characters/utf8.go:183:2, strconv.ParseUint: parsing "b10000000": invalid syntax
2023/08/17 14:36:40 warning: failed to evaluate const hicb at /Users/panz/go/1.20.1/pkg/mod/github.com/pelletier/go-toml/v2@v2.0.8/internal/characters/utf8.go:184:2, strconv.ParseUint: parsing "b10111111": invalid syntax
2023/08/17 14:36:40 Generating utils.HTTPError
2023/08/17 14:36:40 Generating controllers.FindBozoCoinResponse
2023/08/17 14:36:40 Generating models.BozoCoin
2023/08/17 14:36:40 Generating gorm.Model
2023/08/17 14:36:40 Generating gorm.DeletedAt
2023/08/17 14:36:40 Generating sql.NullTime
2023/08/17 14:36:40 Generating utils.Message
2023/08/17 14:36:40 Generating models.CreateBozoCoinInput
2023/08/17 14:36:40 Generating controllers.CreateBozoCoinResponse
2023/08/17 14:36:40 Generating models.DeleteBozoCoinInput
2023/08/17 14:36:40 Generating controllers.DeleteBozoCoinResponse
2023/08/17 14:36:40 Generating controllers.FindGroupsResponse
2023/08/17 14:36:40 Generating models.Group
2023/08/17 14:36:40 Generating models.User
2023/08/17 14:36:40 Generating models.ReverseBozoCoin
2023/08/17 14:36:40 Generating models.UserAchievement
2023/08/17 14:36:40 Generating models.CreateGroupInput
2023/08/17 14:36:40 Generating controllers.CreateGroupResponse
2023/08/17 14:36:40 Generating controllers.DeleteGroupResponse
2023/08/17 14:36:40 Generating controllers.LivenessResponse
2023/08/17 14:36:40 Generating models.AdminUserLoginInput
2023/08/17 14:36:40 Generating controllers.LoginResponse
2023/08/17 14:36:40 Generating controllers.ReadinessResponse
2023/08/17 14:36:40 Generating controllers.FindReverseBozoCoinResponse
2023/08/17 14:36:40 Generating models.CreateReverseBozoCoinInput
2023/08/17 14:36:40 Generating controllers.CreateReverseBozoCoinResponse
2023/08/17 14:36:40 Generating models.DeleteReverseBozoCoinInput
2023/08/17 14:36:40 Generating controllers.DeleteReverseBozoCoinResponse
2023/08/17 14:36:40 Generating controllers.FindUsersResponse
2023/08/17 14:36:40 Generating models.CreateUserInput
2023/08/17 14:36:40 Generating controllers.CreateUserResponse
2023/08/17 14:36:40 Generating controllers.DeleteUserResponse
2023/08/17 14:36:40 create docs.go at docs/docs.go
2023/08/17 14:36:40 create swagger.json at docs/swagger.json
2023/08/17 14:36:40 create swagger.yaml at docs/swagger.yaml

This warning may be irrelevent warning: failed to evaluate const locb at /Users/panz/go/1.20.1/pkg/mod/github.com/pelletier/go-toml/v2@v2.0.8/internal/characters/utf8.go:183:2, strconv.ParseUint: parsing "b10000000": invalid syntax

Sample controller func :

type FindGroupsResponse struct {
    Data []models.Group `json:"data"`
}

// FindGroups godoc
//
//  @Summary        Find Groups
//  @Description    Retrieve a list of all groups along with their associated users.
//  @Tags           Groups
//  @Accept         json
//  @Produce        json
//  @Success        200 {object}    FindGroupsResponse
//  @Failure        400 {object}    utils.HTTPError
//  @Failure        500 {object}    utils.HTTPError
//  @Router         /groups [get]
func (c *Controller) FindGroups(ctx *gin.Context) {
    var groups []models.Group
    if err := c.Database.Preload("Users").Find(&groups).Error; err != nil {
        utils.NewError(ctx, 500, err)
        return
    }

    // Append Group data to to FindGroupsResponse
    var response FindGroupsResponse
    response.Data = groups

    // Return group data
    ctx.JSON(200, response)
}
PauloYR commented 1 year ago

Same issue here, project structure :

├── README.md
├── controllers
│   ├── bozo-coin.go
│   ├── controller.go
│   ├── default-route.go
│   └── user.go
├── docs
│   ├── docs.go
│   ├── swagger.json
│   └── swagger.yaml
├── go.mod
├── go.sum
├── license
├── main.go
├── metrics
│   ├── bozo-coin.go
│   └── metrics.go
├── models
│   ├── bozo-coin.go
│   ├── models.go
│   └── user.go
└── utils
    ├── db-connection.go
    ├── error.go
    └── message.go

Go version : 1.18.10 (also tried in 1.20.1 and 1.17.10) Swag version 1.8.10

Output json :

{
    "swagger": "2.0",
    "info": {
        "description": "A Bozo coin management service API in Go using Gin framework, storing data in PostgreSQL and using Prometheus for metrics.",
        "title": "Bozo API",
        "contact": {
            "name": "Bozo Support",
            "url": "https://danstonkube.fr",
            "email": "contact@danstonkube.fr"
        },
        "license": {
            "name": "Apache 2.0",
            "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
        },
        "version": "1.0"
    },
    "basePath": "/api/v1",
    "paths": {}
}

Obtained by running :

swag init --pd -g main.go

I have the same problem

PauloYR commented 1 year ago

Mitrate to version 1.7.0

Work to me

2023/08/17 14:35:10 Generate swagger docs.... 2023/08/17 14:35:10 Generate general API Info, search dir:./ 2023/08/17 14:35:11 Generating model.PayLoadData 2023/08/17 14:35:11 create docs.go at docs/docs.go 2023/08/17 14:35:11 create swagger.json at docs/swagger.json 2023/08/17 14:35:11 create swagger.yaml at docs/swagger.yaml

go clean -i github.com/swaggo/swag/cmd/swag go install github.com/swaggo/swag@v1.7.0

owais1412 commented 1 year ago

Mitrate to version 1.7.0

Work to me

2023/08/17 14:35:10 Generate swagger docs.... 2023/08/17 14:35:10 Generate general API Info, search dir:./ 2023/08/17 14:35:11 Generating model.PayLoadData 2023/08/17 14:35:11 create docs.go at docs/docs.go 2023/08/17 14:35:11 create swagger.json at docs/swagger.json 2023/08/17 14:35:11 create swagger.yaml at docs/swagger.yaml

go clean -i github.com/swaggo/swag/cmd/swag go install github.com/swaggo/swag@v1.7.0

Mine works if I downgrade to v1.8.2 or less. But v1.8.3 onwards the swag build time is improved. The point is to able to use the latest versions.

rohodo commented 11 months ago

I think I was running into a similar thing and it turned out that I was adding an extra space or newline in between my doc comments and my function definition. at least for me that seemed to be the issue and just posting in case this helps

linliyuan commented 9 months ago

Mitrate to version 1.7.0 Work to me

2023/08/17 14:35:10 Generate swagger docs.... 2023/08/17 14:35:10 Generate general API Info, search dir:./ 2023/08/17 14:35:11 Generating model.PayLoadData 2023/08/17 14:35:11 create docs.go at docs/docs.go 2023/08/17 14:35:11 create swagger.json at docs/swagger.json 2023/08/17 14:35:11 create swagger.yaml at docs/swagger.yaml

go clean -i github.com/swaggo/swag/cmd/swag go install github.com/swaggo/swag@v1.7.0

Mine works if I downgrade to v1.8.2 or less. But v1.8.3 onwards the swag build time is improved. The point is to able to use the latest versions.

I encountered the same problem, and when I introduced the vendor dependency in main.go, the generation speed changed from one minute to one second.

evan-goode commented 6 months ago

In my case empty paths were due to runtime.GOROOT() producting an empty string (and, I believe, since swag ignores all paths with runtime.GOROOT() prefix, it ignored all of them). The reason runtime.GOROOT() would be empty could be b/c of the way swag is built. In my case it was a nix package, with this issue: NixOS/nixpkgs#224701

I'm using go-swag from nixpkgs and I had the same problem, as a workaround I'm invoking swag with:

(source <(go env) && swag init)

in my Makefile.

GirishBhutiya commented 4 months ago

Same at my end with 1.16.3.

Is there any solution to it? I am using the go-chi router.

Thanks