1. step 1 related command(download swagger, then use related command)
go mod init xxx(this name you can give any name, up to you)------ generate go.mod automatically
Go build main.go (update go.mod file and create go.sum file automatically)
When you import a new package, you need to use command "go mod vendor" to download
2. step 2 main.go code
package main
import (
// "github.com/swaggo/swag/example/celler/controller"
// _ "github.com/swaggo/swag/example/celler/docs"
_ "xxx/docs"
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
"fmt"
"net/http"
)
// @Summary
// @title Swagger Example API
// @version 0.0.1
// @description This is a sample server Petstore server.
// @NAME get-string-by-int
// @Host 127.0.0.1:8001
// @Accept json
// @Produce json
// @Success 200
// @Security ApiKeyAuth
// @Security OAuth2Application[write, admin]
// @Router /print [get]
func Print(w http.ResponseWriter, r *http.Request) {
// var (
// name string
// )
// id := context.Param("name")
fmt.Println("hello world")
// context.JSON(http.StatusOK, gin.H{
// "code": http.StatusOK,
// "msg": "success",
// "data": name,
// })
// context.JSON(http.StatusOK, "account")
}
// @title Swagger Example API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8001
// @query.collection.format multi
// @securityDefinitions.basic BasicAuth
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization
// @securitydefinitions.oauth2.application OAuth2Application
// @tokenUrl https://exampleeeeeeeeeee.com/oauth/token
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information
// @securitydefinitions.oauth2.password OAuth2Password
// @tokenUrl https://example.com/oauth/token
// @scope.read Grants read access
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information
func main() {
// r:= gin.New()
r.GET("/print", Print)
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run(":8001")
}
2. use swag init command to generate related files.
本文档介绍了如何使用Golang和Gin-Swagger搭建RESTful API。首先通过`go mod init`创建项目,然后利用`go mod vendor`下载依赖。在`main.go`中设置Swagger元数据并引入必要包。定义了名为`Print`的HTTP GET路由,然后使用`swag init`命令生成相关Swagger文件。最后运行服务器监听8001端口。
6930

被折叠的 条评论
为什么被折叠?



