First I recommend a good go-GIN basics tutorialwww.jianshu.com/p/a31e4ee25…

My application of GO-GIN in my own projects starts from the project structure

  • Common Common methods, global variables
  • Config Configuration file
  • Controller MVC c, write router control method
  • Database Database connection
  • Middleware middleware
  • M for Model MVC, declaration structure, data processing (using database)
  • The router routing
  • Utiles toolclass methods (encapsulation of methods such as timing, encryption)
  • Mian entrance

With this relatively generic and simple Web project structure in place, it’s time to fill in the code. Why talk about go-GIN but talk about project structure? Because GO-gin was only used for the Router and controller in my project. The front and back are separated so you don’t have a view here, so you don’t use some of the functionality of the framework.

Use of GO-gin in the Router

// Init Initializes the route
func Init(a) {
	router := gin.Default()
	// cross-domain processing, options request processing
	router.Use(middleware.CrossDomain())
	// V1 group is open to anyone
	v1 := router.Group("/v1")
	{
		v1.POST("/login", user.Login)
		v1.POST("/register", user.Register)
		v1.GET("/index", index.GetInfo)
		v1.GET("/posts", post.GetPosts)
		v1.GET("/post", post.GetPost)
	}

	v2 := router.Group("/v2")
	// V2 groups use the middleware AuthMiddleWare, which requires token permission to request
	v2.Use(middleware.AuthMiddleWare())
	{
		v2.POST("/publish", post.Publish)
		v2.POST("/isload", user.IsLoad)
		v2.POST("/reply1", post.Reply1)
		v2.POST("/reply2", post.Reply2)
	}
	router.Run(": 8000")}Copy the code

Uppercase Init determines when to call it in main, and lowercase Init initializes automatically. Gin.Default() gets the routing object, and router.use hangs a piece of middleware on the total route. This middleware is designed to solve cross-domain and options requests, and all front-end requests must go through this middleware. V1 and V2 are the two routing groups defined. I hung middleware requiring token verification on group V2, but no hung middleware on group V1 is open to everyone. V1 and v2 there’s a pair of curly braces that don’t really do anything but modify the code format. The second parameter in the request method is defined in controller. Finally, Run a port for the back-end service.

Declare structures in model

Ex. :

// Reply1 .
type Reply1 struct {
	ID        	bson.ObjectId `json:"id"`
	ShareMsg    `bson:",inline"`
}

// Reply2 .
type Reply2 struct {
	ID        	bson.ObjectId  `json:"id"`
	RID         bson.ObjectId  `json:"rid"`
	RName 		string 		   `json:"rName"`
	Show		bool		   `json:"show"`
	ShareMsg	`bson:",inline"`
}

// ShareMsg .
type ShareMsg struct {
	HeadImg		string		`json:"headImg"`
	UName 		string 		`json:"uName"`
	CreateTime 	string			`json:"createTime"`
	Content    	string    		`json:"content"`
	TID        	bson.ObjectId   `json:"tid"`
}
Copy the code

The code is out of shape in the pasting process. Here are some JSON tags that correspond to the same (crucially) property names in the PREVIOUS JSON object. Bson: inline tag. If mongodb is used, ShareMsg will be stored in the database as a nested object when saving the object. The bson.ObjectId type is also used here. There is a method in bson to generate a relatively unique ID that is easy to use and needs to be received.

Use of GO-gin in Controller

// Reply1 A primary reply
func Reply1(c *gin.Context) {
   reply1 := &model.Reply1{}
   iferr := c.Bind(reply1); err ! =nil {
   	fmt.Println(err.Error())
   	return
   }
   reply1.UName = c.Request.Header["Authorization"] [0]
   reply1.CreateTime = utils.GetTimeStr()
   reply1.ID = bson.NewObjectId()
   if reply1.Save(reply1.TID) {
   	c.JSON(http.StatusOK, gin.H{
   		"reply": *reply1,
   	})
   } else {
   	c.String(http.StatusOK, "Internal error")}}Copy the code
  • Define the structure object reply1, use C.bind (Reply1) to perfectly bind the json object transferred from the front end to the back end structure object, where the back end defines the properties that the front end does not have, the default data type is 0, the rest is empty. Find the specific use method by yourself.
  • Front-end does not pass JSON object, use URL or form parameters request, back-end processing method see the beginning of the article, not detailed.
  • As for the request to return to the front end, I will use JSON objects as long as the data is carried. Please refer to the method provided by GO-gin in the section of C. SON in the code. If you simply tell the front end and back end some status directly C. strand returns the status code and string.

So much for the introduction of go-gin for personal use. Is it very brief? If you have any better use methods and opinions on GO-GIN, please reply and discuss with me. In the next article, I plan to write some usage and pit mining records of MGO in GO.