当前位置:网站首页>gin 路由,参数,输出
gin 路由,参数,输出
2022-07-29 06:20:00 【Mar丶流年】
文章目录
安装
go get -u github.com/gin-gonic/gin
官方例子
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
路由
gin.Default() 和 gin.New() 区别
// gin.Default
func Default() *Engine {
debugPrintWARNINGDefault()
engine := New()
engine.Use(Logger(), Recovery())
return engine
}
通过上面代码可得知,gin.Default() 创建的路由器会使用日志和错误发现中间件
路由分组
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
// 通过 Group(relativePath) 进行分组
// relativePath:前缀
group := r.Group("/api")
//访问 /api/ping
group.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
r.Run()
}
路由参数
动态路由参数
通过 “:” + 参数名 或通过 星号 + 参数名 设置动态参数
星号 + 参数名 会将 其”/“后的所有path都赋值到该参数中
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
//通过 ":" + 参数名 设置动态参数
r.GET("/ping/:controller/:action", func(c *gin.Context) {
//从gin.Context 中通过 param(参数名) 获取动态参数值
c.JSON(http.StatusOK, gin.H{
"message": "pong",
"controller": c.Param("controller"),
"action": c.Param("action"),
})
})
//通过 "*" + 参数名设置动态参数
r.GET("/look/:controller/*action", func(c *gin.Context) {
//从gin.Context 中通过 param(参数名) 获取动态参数值
//访问 localhost:8080/look/good/list/a/b/c
c.JSON(http.StatusOK, gin.H{
"message": "pong",
"controller": c.Param("controller"),
// action: /list/a/b/c
"action": c.Param("action"),
})
})
r.Run(":8080")
}
动态参数验证
gin.Context 提供 ShouldBindUri(obj) 对参数进行验证,参数验证失败返回error,obj 提供验证规则,验证通过后,动态参数可以通过obj中的属性获取
obj中的属性名自定义即可,类型即对应动态参数类型 通过 “参数描述” 通过参数描述对其做其它限制,如:
//Id是obj属性名
//int是Id类型也对应限制动态参数类型
//string后的`.....`中为参数描述
//uri:"id" 代表其对应url中的:id或*id,和obj属性的对应关系
//binding:后的为绑定规则,required:要求必填写
type Ping struct {
Id int `uri:"id" binding:"required"`
}
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Ping struct {
Controller string `uri:"controller" binding:"required"`
Action string `uri:"action" binding:"required"`
Id int `uri:"id" binding:"required"`
}
func main() {
r := gin.Default()
r.GET("/ping/:controller/:action/:id", func(c *gin.Context) {
p := &Ping{
}
err := c.ShouldBindUri(p)
if err != nil {
//不符合路由规则,给其返回找不到的错误码404
c.Status(404)
return
}
c.JSON(http.StatusOK, gin.H{
"message": "pong",
"controller": c.Param("controller"),
"action": c.Param("action"),
"id": c.Param("id"),
})
})
r.Run(":8080")
参数
一般分为三种参数:
1.路由参数,组成路由的一部分
2.GET请求的参数
3.POST请求的参数
获取GET参数
gin.Context 提供了DefaultQuery(key,value) 和 Query(key) 获取GET参数,DefaultQuery 比 Query 多一个设置默认值功能
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
controller := c.DefaultQuery("controller", "default_controller")
action := c.DefaultQuery("action", "default_action")
c.JSON(http.StatusOK, gin.H{
"message": "pong",
"controller": controller,
"action": action,
})
})
r.Run(":8080")
}
获取POST参数
gin.Context 提供了 DefaultPostForm(key,value) 和 PostForm(key) 获取POST参数,DefaultPostForm 比 PostForm 多一个设置默认值功能
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.POST("/ping", func(c *gin.Context) {
controller := c.DefaultPostForm("controller", "default_controller")
action := c.DefaultPostForm("action", "default_action")
c.JSON(http.StatusOK, gin.H{
"message": "pong",
"controller": controller,
"action": action,
})
})
r.Run(":8080")
}
输出
输出JSON
通过 gin.Context 提供的 JSON(code,obj) 输出JSON格式
obj支持两种类型:
- gin.H 即 map[string]any
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK,gin.H{
"message":"输出普通JSON",
})
})
r.Run(":8080")
}
- struct
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Data struct {
Message string
Code int `json:"status_code"`
}
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
//{"Message":"结构体转换","status_code":200}
//输出status_code是因为设置JSON tag `json:"status_code"`
// Code 转换为 status_code
c.JSON(http.StatusOK,Data{
Message: "结构体转换",
Code: 200,
})
})
r.Run(":8080")
}
输出ProtoBuf
gin.Context 提供 ProtoBuf(code int, obj any) 输出 ProtoBuf
编写proto文件
//trip.proto
syntax = "proto3";
package xie;
option go_package = ".;trippb";
message CreateTripRequest{
string message = 1;
int64 status_code = 2;
}
通过proto生成结构体 trip.pb.go
需要下载proto工具(https://github.com/protocolbuffers/protobuf/releases)
protoc -I=. --go_out=paths=source_relative:./ trip.proto
输出ProtoBuf
package main
import (
trippb "ServiceProxy/public/proto"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.ProtoBuf(http.StatusOK,&trippb.CreateTripRequest{
Message: "666",
StatusCode: 200,
})
})
r.Run(":8080")
}
访问浏览器会下载得到ping文件(移动ping 到 /Users/xieruixiang/go/src/ServiceProxy/public/ping)
通过 proto.Unmarshal 还原ping文件内容到protobuf结构体
package main
import (
trippb "ServiceProxy/public/proto"
"fmt"
"google.golang.org/protobuf/proto"
"os"
)
func main() {
file, err := os.ReadFile("/Users/xieruixiang/go/src/ServiceProxy/public/ping")
if err != nil {
panic(err)
}
m := &trippb.CreateTripRequest{
}
proto.Unmarshal(file, m)
//666,200
fmt.Println(m.Message,m.StatusCode)
}
输出PureJSON
与JSON相比,PureJSON会将特殊的HTML字符进行unicode编码,可以直接进行html的原样输出
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.PureJSON(http.StatusOK, gin.H{
"html": ` <div><button style="color:red;">submit</button></div> `,
})
})
r.Run(":8080")
}
边栏推荐
- Simulation volume leetcode [normal] 222. number of nodes of complete binary tree
- Simulation volume leetcode [normal] 061. rotating linked list
- Leetcode-592: fraction addition and subtraction
- Share some tips for better code, smooth coding and improve efficiency
- 说一下 TCP/IP 协议?以及每层的作用?
- Cesium反射
- 实现改变一段文字的部分颜色效果
- mysql可以定时导出表格吗?
- 数据库多表查询 联合查询 增删改查
- 外包干了3年,跳槽后转自动化测试工资是原来的2倍,秘诀原来是......
猜你喜欢

The core of openresty and cosocket

buck电路boot和ph引脚实测

10 frequently asked JVM questions in interviews

Cvpr2022oral special series (I): low light enhancement

线程 - 线程安全 - 线程优化

Student status management system based on C language design

聊天机器人有何用处?有何类型?看完这些就明白了!

Thread - thread safety - thread optimization

线程同步—— 生产者与消费者、龟兔赛跑、双线程打印

Teacher wangshuyao's notes on operations research 04 fundamentals of linear algebra
随机推荐
Junda technology | applicable to "riyueyuan" brand ups wechat cloud monitoring card
实战!聊聊如何解决MySQL深分页问题
'function VTable for error: undefined reference to... 'cause and solution of the problem
MVFuseNet:Improving End-to-End Object Detection and Motion Forecasting through Multi-View Fusion of
IO流 - File - properties
[C language brush leetcode] 2332. The latest time to get on the bus (m)
Sword finger offer II 115: reconstruction sequence
新同事写了几段小代码,把系统给搞崩了,被老板爆怼一顿!
Pod基本介绍
Teacher Wu Enda machine learning course notes 05 octave tutorial
Flink实时仓库-DWD层(处理复杂数据-流和表的装换处理)模板代码
游戏资产的革命
数组的子集不能累加出的最小正数
Flink实时仓库-DWD层(交易域-加购维度退化处理)模板代码
[C language brush leetcode] 67. binary sum (E)
Teacher Wang Shuyao's notes on operations research 09 linear programming and simplex method (Application of simplex table)
Summary of 2022 SQL classic interview questions (with analysis)
The difference between pairs and ipairs
Teacher Wu Enda's machine learning course notes 00 are written in the front
数据库持久化+JDBC数据库连接