当前位置:网站首页>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")
}
边栏推荐
- 【解决方案】ERROR: lib/bridge_generated.dart:837:9: Error: The parameter ‘ptr‘ of the method ‘FlutterRustB
- 实现改变一段文字的部分颜色效果
- Dbasql interview questions
- 【C语言刷LeetCode】67. 二进制求和(E)
- [C language brush leetcode] 67. binary sum (E)
- Teacher wangshuyao's notes on operations research 04 fundamentals of linear algebra
- [cf1054h] epic Revolution -- number theory, convolution, arbitrary modulus NTT
- C language memory stack and heap usage
- 【charles日常问题】开启charles,使用不了钉钉
- 330. 按要求补齐数组
猜你喜欢

Teacher Wu Enda's machine learning course notes 02 univariate linear regression

How to write controller layer code gracefully?

ECCV 2022丨轻量级模型架ParC-Net 力压苹果MobileViT代码和论文下载

Thread - thread safety - thread optimization

Student status management system based on C language design

基于C语言设计的学生成绩排名系统

做开发4年13K,想转行自动化测试,薪资还能涨吗···

Connecting PHP 7.4 to Oracle configuration on Windows

MySQL:当你CRUD时BufferPool中发生了什么?十张图就能说清楚

上采样之反卷积操作
随机推荐
实战!聊聊如何解决MySQL深分页问题
Leetcode-592: fraction addition and subtraction
Teacher wangshuyao wrote the notes of operations research course 00 in the front
buck电路boot和ph引脚实测
Talk about tcp/ip protocol? And the role of each layer?
Unity free element special effect recommendation
Teacher wangshuyao's notes on operations research 02 fundamentals of advanced mathematics
leetcode-592:分数加减运算
外包干了3年,跳槽后转自动化测试工资是原来的2倍,秘诀原来是......
Federal learning backdoor attack summary (2019-2022)
MySQL queries are case sensitive
Sword finger offer II 115: reconstruction sequence
Flink实时仓库-DWD层(下单-多张表实现join操作)模板代码
HJ37 统计每个月兔子的总数 斐波那契数列
SSH password free login - two virtual machines establish password free channel two-way trust
模拟卷Leetcode【普通】222. 完全二叉树的节点个数
mysql可以定时导出表格吗?
谷歌零碎笔记之JWT(草稿)
Student status management system based on C language design
JVM之垃圾回收机制(GC)