I want to use Swagger for my RESTFul API Documentation from Go and Gin.
I have this code in main.go: package main
import (
"gowebservice/config"
"gowebservice/controllers"
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
_ "github.com/swaggo/gin-swagger/example/basic/docs"
)
// @title Students API
// @version 1.0
// @description This is a basic API Students using Gin and Gorm.
// @host localhost:8080
// @BasePath /
func main() {
r := gin.Default()
config.ConnectDatabase()
v1 := r.Group("/api/v1")
{
v1.GET("students/all", controllers.GetStudents)
}
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run()
}
and this is my endpoint that have GET method:
package controllers
import (
"gowebservice/config"
"gowebservice/models"
"net/http"
"github.com/gin-gonic/gin"
)
// GetStudents godoc
// @Summary Show a list of students
// @Accept json
// @Produce json
// @Router /students [get]
func GetStudents(c *gin.Context) {
var students []models.Student
if err := config.DB.Find(&students).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
return
}
c.JSON(http.StatusOK, students)
}
When I used swag init
and go run main.go
, Swagger UI still showing the example not my endpoint.
Anyone can help me?
I ran into this too 😅
The issue is that we imported the basic example docs:
import (
...
_ "github.com/swaggo/gin-swagger/example/basic/docs"
)
You need to change that to the docs package that was generated by swag init
.
Assuming your module name is gowebservice
, then:
import (
...
_ "gowebservice/docs"
)
Running go run main.go
after that should make Swagger UI find your own documentation instead! :D