"github.com/marmotedu/gopractise-demo/swagger/api" // This line is necessary for go-swagger to find your docs! _ "github.com/marmotedu/gopractise-demo/swagger/docs" )
var users []*api.User
funcmain() { r := gin.Default() r.POST("/users", Create) r.GET("/users/:name", Get)
log.Fatal(r.Run(":5555")) }
// Create create a user in memory. funcCreate(c *gin.Context) { var user api.User if err := c.ShouldBindJSON(&user); err != nil { c.JSON(http.StatusBadRequest, gin.H{"message": err.Error(), "code": 10001}) return }
for _, u := range users { if u.Name == user.Name { c.JSON(http.StatusBadRequest, gin.H{"message": fmt.Sprintf("user %s already exist", user.Name), "code": 10001}) return } }
// Get return the detail information for a user. funcGet(c *gin.Context) { username := c.Param("name") for _, u := range users { if u.Name == username { c.JSON(http.StatusOK, u) return } }
c.JSON(http.StatusBadRequest, gin.H{"message": fmt.Sprintf("user %s not exist", username), "code": 10002}) }
Required: true,生成的 Swagger 文档会声明该字段为必须字段
api/user.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Package api defines the user model. package api
// User represents body of User request and response. type User struct { // User's name. // Required: true Name string`json:"name"`
// swagger:route POST /users user createUserRequest // Create a user in memory. // responses: // 200: createUserResponse // default: errResponse
// swagger:route GET /users/{name} user getUserRequest // Get a user from memory. // responses: // 200: getUserResponse // default: errResponse
// swagger:parameters createUserRequest type userParamsWrapper struct { // This text will appear as description of your request body. // in:body Body api.User }
// This text will appear as description of your request url path. // swagger:parameters getUserRequest type getUserParamsWrapper struct { // in:path Name string`json:"name"` }
// This text will appear as description of your response body. // swagger:response createUserResponse type createUserResponseWrapper struct { // in:body Body api.User }
// This text will appear as description of your response body. // swagger:response getUserResponse type getUserResponseWrapper struct { // in:body Body api.User }
// This text will appear as description of your error response body. // swagger:response errResponse type errResponseWrapper struct { // Error code. Code int`json:"code"`