这是我参与「第五届青训营 」笔记创作活动的第4天
前言:最近写项目需要了解Gin这个http框架,同时对之前课的补充实践。本篇不讨论深入的技术细节,只为了快速上手。
一.基础知识
1.HTTP协议
百科的定义:HTTP协议(超文本传输协议)是一种网络通信协议,它允许将超文本标记语言(HTML)文档从Web服务器传送到客户端的浏览器。 简单来说,就是个通讯方法。比如打电话,发短信,发微信···方式不一样,但是能联络到对方。而且大部分web基于http/https协议。 http协议由两大部分组成,请求和响应。
图片来源网络
HTTP协议的请求方法有GET、POST、HEAD、PUT、DELETE、OPTIONS、TRACE、CONNECT。
图片来源网络
状态码:
图片来源网络
请求和响应方法随语言的语法而决定,但是都遵循http格式,这里不做叙述。
2. 何为HTTP框架
HTTP框架负责的就是对HTTP请求的解析、根据对应的路由选择对应的后端逻辑.见图
图片来源网络
3.gin框架
中间件是Gin的精髓。一个个中间件组成一条中间件链,对HTTP Request请求进行拦截处理。作用:
- Web请求到到达我们定义的HTTP请求处理方法之前,拦截请求并进行相应处理(比如:权限验证,数据过滤等),这个可以类比为前置拦截器或前置过滤器;
- 在我们处理完成请求并响应客户端时,拦截响应并进行相应的处理(比如:添加统一响应部头或数据格式等),这可以类型为后置拦截器或后置过滤器。
二.函数基础
1.gin.Default()
这里会返回使用一个默认的中间件的对象,Recovery和Logger。你也可以gin.new()返回一个不带有中间件的gin.Engine对象。
func Default() *Engine {
debugPrintWARNINGDefault()
engine := New()
engine.Use(Logger(), Recovery())
return engine
}
2.gin.Context
一个结构体,里面封装了http的请求。go没有类这一数据结构,但是结构体的用法可以媲美。
// 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
skippedNodes *[]skippedNode
// 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
}
3.gin.H
等价于这一段代码:map[string]interface{}, 也就是可以简化生成json格式
4.gin.Context.JSON()
// JSON serializes the given struct as JSON into the response body.
// It also sets the Content-Type as "application/json".
func (c *Context) JSON(code int, obj interface{}) {
c.Render(code, render.JSON{Data: obj})
}
其中render是render包里面的函数,支持对json的快速响应。
三.简易项目
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/hello", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "hello,world_get",
})
})
r.POST("/hello", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "hello,world_post",
})
})
r.PUT("/hello", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "hello,world_put",
})
})
r.DELETE("/hello", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "hello,world_delete",
})
})
r.Run()
}
调试建议用postman或者apifox,浏览器只支持Get和Post请求