Defining structure

Define a request and response structure

type CreateRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

type CreateResponse struct {
	Username string `json:"username"`
}
Copy the code

Read the request

Gin provides us with several apis for reading requests

  • Param() : returns URL parameter values, such as /user/:id
  • Query() : Reads address parameters in the URL, such as GET /path? id=1234&name=Manu&value=
  • DefaultQuery() : Similar to Query(), but returns a default value if key is not present, such as GET /? name=Manu&lastname=
  • Bind() : Examines the content-Type and parses the message body as the specified format into the Go Struct variable. Apiserver uses A JSON media type, so Bind() is resolved in JSON format.
  • GetHeader() : Gets the HTTP header.
  1. Read the information we need from the request
	var r CreateRequest
	err := c.Bind(&r)
	iferr! =nil{
		handler.SendResponse(c,errno.ErrBind,nil)
		return
	}
	user := c.Param("username")
	log.Printf("URL username: %s",user)

	desc := c.Query("desc")
	log.Printf("URL key param desc: %s", desc)

	contentType := c.GetHeader("Content-Type")
	log.Printf("Header Content-Type: %s", contentType)
	log.Printf("username is: [%s], password is [%s]", r.Username, r.Password)
Copy the code
  1. Based on the information read, determine the content of the response returned
        if r.Username == "" {
		handler.SendResponse(c, errno.New(errno.ErrUserNotFound, fmt.Errorf("username can not found in db: xx.xx.xx.xx")), nil)
		return
	}

	if r.Password == "" {
		handler.SendResponse(c, fmt.Errorf("password is empty"), nil)
	}

	rsp := CreateResponse{
		Username: r.Username,
	}

	handler.SendResponse(c,nil,rsp)
Copy the code

Returns a response

  1. Response body with error message
type Response struct {
	Code int `json:"code"`
    Message string `json:"message"`
	Data interface{} `json:"data"`
}

Copy the code
  1. Encapsulate the error message in the response body as well
func SendResponse(c *gin.Context,err error,data interface{})  {
	code, message := errno.DecodeErr(err)
     c.JSON(http.StatusOK,Response{Code: code,Message: message,Data: data})

}
Copy the code

test

  1. The test sample

  1. The test results