Day16 Gin's Routing Structure And Context

Gin's Item Structure

|-app
    |-common 公共方法
        |-display.go 统一json格式输出
    |-config 配置文件和统一路由管理
        |-message.yml 状态码文件
        |-route.go 路由配置文件
    |-controller 控制器
    |-dao database crud
    |-middleware 中间件
    |-model 模型
    |-service 核心业务
|-main.go 程序执行入口

大致上Gin Backend Service的 Item hierarchic会长这样,但目前应该有许许多多的file是读者完全不懂的,没关系我们後面会依序地慢慢补上,这章节主要还是会环绕着route.gomain.goservice.go来解说

service.go

这边主要是放api收到request後续所要执行的服务行为与response等

package app

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type UsersController struct {}

func NewUsersController() UsersController {
	return UsersController{}
}

func QueryUsersController() UsersController {
	return UsersController{}
}

func (u UsersController) CreateUser (c *gin.Context){
	c.JSON(http.StatusOK, gin.H{
		"status": 0,
		"msg":    "success Register",
		"data":   nil,
	})
}

func (u UsersController) GetUser (c *gin.Context){
	c.JSON(http.StatusOK, gin.H{
		"status": 0,
		"msg":    "success get data",
		"data":   nil,
	})
}
  • 首先,我们透过struct与继承的方式,去定义不同行为的执行者为谁。
  • 接下来则是让service method继承该执行者,并完成该Service与Response。

route.go

这边则是放URL的规则与匹配路径,以及该动作後续的执行行为等

package config

import (
	"github.com/gin-gonic/gin"
	"ironman-2021/app"
)

func RouteUsers(r *gin.Engine) {
	posts := r.Group("/v1/users")
	{
		posts.POST("/", app.NewUsersController().CreateUser)
		posts.GET("/", app.QueryUsersController().GetUser)
	}
}
  • 我们这边先创一个group url叫做/v1/users
  • 後面再定义他的postfix以及不同method所会执行的行为

main.go

最後则是main.go,我们创造一个gin.Default(),并除了health check api以外,我们也将其串连上了前面的RouteUsers()

package main

import (
	"github.com/gin-gonic/gin"
	"ironman-2021/app/config"
)
func main() {
	app := gin.Default()
	app.GET("/hc", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "health check",
		})
	})
	config.RouteUsers(app)
	err := app.Run(":8080")
	if err != nil {
		panic(err)
	}
}

Code Structure

最後的程序码结构则会长这样

.
|____go.mod
|____app
| |____service.go
| |____config
| | |____route.go
|____go.sum
|____main
|____main.go
|____.idea
| |____iron-man-2021.iml
| |____.gitignore
| |____workspace.xml
| |____modules.xml

Gin Context

最後则是来讲解下,前面一直使用到的parameter gin.Context

// Context is the most important part of gin. It allows us to pass variables between middleware,
// manage the flow, validate the JSON of a request and render a JSON response for example.
type Context struct {
	writermem responseWriter
	Request   *http.Request
	Writer    ResponseWriter

	Params   Params
	handlers HandlersChain
	index    int8
	fullPath string

	engine *Engine
	params *Params

	// This mutex protect Keys map
	mu sync.RWMutex

	// Keys is a key/value pair exclusively for the context of each request.
	Keys map[string]interface{}

	// Errors is a list of errors attached to all the handlers/middlewares who used this context.
	Errors errorMsgs

	// Accepted defines a list of manually accepted formats for content negotiation.
	Accepted []string

	// queryCache use url.ParseQuery cached the param query result from c.Request.URL.Query()
	queryCache url.Values

	// formCache use url.ParseQuery cached PostForm contains the parsed form data from POST, PATCH,
	// or PUT body parameters.
	formCache url.Values

	// SameSite allows a server to define a cookie attribute making it impossible for
	// the browser to send this cookie along with cross-site requests.
	sameSite http.SameSite
}

官方package当中已经有annotation明确指出,每个不同变数的用途已经定义,那这边就不一一赘述。

简单来说gin.Context就是把Request和Response做一个结构性的管理,但这也是建立在gin已经对於HTTP Request以以及Response进行了一定程度的封装,才能做到如此的简洁以及乾净。

Summary

这章节主要是介绍Gin的程序码放置与分类方式,以及Router的基本应用等,详细程序码则会放在以下连结。

https://github.com/Neskem/Ironman-2021/tree/Day-16


<<:  Day 16 - UML x Interface — TextField

>>:  Day19 vue.js之我的专案显示

【在厨房想30天的演算法】Day 06 资料结构:连结串列 Linked List

Aloha!又是我少女人妻 Uerica ,今天中秋节大家吃肉了吗!传说中后羿的狗狗偷吃了嫦娥吃剩的...

零基础也能学会的9个Excel函数,进阶必备!

今天给大家分享9个Excel语法常用的公式,可以有效的解决Excel中办公所需,0基础也可以轻松学会...

Pascal 语言和你 SAY HELLO!!

第二十七天 各位点进来的朋友,你们好阿 小的不才只能做这个系列的文章,但还是希望分享给点进来的朋友,...

<Day9> Contract — 取得期货(Futures)资讯

● 这章将以模拟帐户来示范如何取得期货(Futures)资讯 回顾上一章,我们学习如何用Contra...

Day04,弄几只API

正文 弄完资料库後,花了一点时间的写了这几只API。 主要的routing分成 API/[Contr...