Go language learning notes - project specification structure adjustment | Web framework Gin

Study notes and write down what is what.

Follow the project built in the previous article: Go language learning notes - configuration file usage, log configuration | Web framework Gin (II)_ Swordsman a Liang_ Liang's blog -CSDN blog

The configuration file and log have been added, which is more consistent with the use of the project.

However, I still want to transform the project structure to the mvc structure similar to java, so that the later code can be standardized. After all, it is impossible to put all the function implementations into the main method.

Project address: github address 

Routing layer adjustment

Add router in app/router directory Go and test_router.go two files.


Router The go file mainly provides initialization summary.

router.go code is as follows:

package router

import "github.com/gin-gonic/gin"

func InitRouter(r *gin.Engine) {
	// Test route

test_ router. The go file is mainly used to configure the routing address of the test control layer.

test_router.go code is as follows:

package router

import (

func TestRouter(r *gin.Engine) {
	r.GET("/", controllers.TestCtrl.HelloWorld)
	r.GET("/test/:name", controllers.TestCtrl.TestParam)
	r.GET("/test1", controllers.TestCtrl.TestDefaultParam)
	r.POST("/testPost", controllers.TestCtrl.TestPost)
	r.POST("/testPost2", controllers.TestCtrl.TestPostBody)

As for the relevant contents of controllers, we will continue to talk about them below.

Control layer adjustment

Add two file controllers Go and test_controller.go.


Where controllers Go is mainly used to declare the object of the structure in the controller, which is convenient to use.

controllers. The code of go is as follows:

package controllers

var (
	TestCtrl = &TestController{}

test_ controller. The code of go is as follows:

package controllers

import (

type TestController struct {

func (t *TestController) HelloWorld(context *gin.Context) {
	log.Logger.Info("test HelloWorld Interface")
	context.String(http.StatusOK, "hello world")

func (t *TestController) TestParam(context *gin.Context) {
	name := context.Param("name")
	log.Logger.Info("test TestParam Interface")
	context.String(http.StatusOK, "check param %s", name)

func (t *TestController) TestDefaultParam(context *gin.Context) {
	name := context.DefaultQuery("name", "Zhang San")
	gender := context.Query("gender")
	log.Logger.Info("test TestDefaultParam Interface")
	context.String(http.StatusOK, "His name is%s,Gender:%s", name, gender)

func (t *TestController) TestPost(context *gin.Context) {
	name := context.PostForm("name")
	nick := context.DefaultPostForm("nick", "leo")
	log.Logger.Info("test TestPost Interface")
	context.JSON(http.StatusOK, gin.H{
		"status": gin.H{
			"code":    http.StatusOK,
			"success": true,
		"name": name,
		"nick": nick,

func (t *TestController) TestPostBody(context *gin.Context) {
	var request req.TestPostRequest
	log.Logger.Info("test TestPostBody Interface")

	if err := context.ShouldBindJSON(&request); err != nil {
		log.Logger.Panic("Parameter exception")

	if _, err := json.Marshal(request); err != nil {
		log.Logger.Panic("Parameter parsing exception")

	context.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"data": request,

This is complicated. The services directory and pojo directory are used, which will be mentioned below. In general, the interface functions previously implemented in the main method have been moved here.

Service layer adjustment

Add services in the app/services directory Go and test_service.go two files, the same as the control layer.

Where services The go file is mainly used to declare the object of the structure in the service for convenience.

services.go code is as follows:

package services

var (
	TestServ = &Test{}

test_service.go code is as follows:

package services

import (

type TestService interface {
	PrintInfo(req *req.TestPostRequest)

type Test struct {

func (t Test) PrintInfo(req *req.TestPostRequest) {
	fmt.Printf("Test data, name=%s,age=%d\n", req.Name, req.Age)

It can be seen that the interface is used, and the structure Test implements the PrintInfo method, which can be combined with test_controller.go file to understand the logic.

Entity adjustment

In the service layer, we can see that we have used an entity, TestPostRequest. We created a req directory under app/pojo and added test_request.go file.


test_request.go code is as follows:

package req

type TestPostRequest struct {
	Name string `json:"name"`
	Age  int    `json:"age"`

Mainmethod adjustment

Adjust the main method as follows:

package main

import (

func main() {
	log.InitLogger(toml.GetConfig().Log.Path, toml.GetConfig().Log.Level)
	log.Logger.Info("config", log.Any("config", toml.GetConfig()))

	r := gin.Default()


Check it out

The project has been changed. Let's test the interface. The startup screenshot is as follows.

The screenshot of the testPosts interface is shown below.

In the right case, let's take a look at the log.

Take a look at the log of parameter exceptions.

OK, no problem.


Later, I will continue to adjust. I see some warnings in the main function. Take your time.

Tags: Go Back-end programming language

Posted by jc_ply on Fri, 03 Jun 2022 01:52:29 +0530