目录

获取header头里的参数:

scene := httpext.GetHeaderByName(ctx, "scene") // online / dev
// @desc 通过上下文获取header中指定key的内容
func GetHeaderByName(ctx *gin.Context, key string) string {
return ctx.Request.Header.Get(key)
}
//获取用户微信信息表里的数据
body, _ := ctx.Get("json")
us.UserWxModel.WxUserInfo = service.BuildNick(body.(string)) /*编码特殊特号*/

httpext包

package httpext

import (
"fmt"
"github.com/gin-gonic/gin"
"io/ioutil"
"linkbook.com/LinkBookGo/lib/apilog"
) // @desc 通过上下文获取header中指定key的内容
func GetHeaderByName(ctx *gin.Context, key string) string {
return ctx.Request.Header.Get(key)
} // @desc 通过上下文获取body内容并将内容写到指定key中
func SetBodyJson(context *gin.Context, key string) {
body, _ := ioutil.ReadAll(context.Request.Body)
apilog.DebugLog("当前请求数据内容:", string(body[:]))
fmt.Println("当前请求的数据:", string(body[:]))
context.Set(key, string(body[:]))
}

方法二:

~~~
//获取body里的数据
func getBodyData(c *server.Context) string {
var bodyBytes []byte
if c.Request.Body != nil {
bodyBytes, _ = ioutil.ReadAll(c.Request.Body)
}
// 把刚刚读出来的再写进去
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
return string(bodyBytes)
}
~~~

https://www.bilibili.com/video/av68769981/?p=2

课程代码:

https://www.qfgolang.com/?special=ginkuangjia&pid=2783

https://www.liwenzhou.com/posts/Go/Gin_framework/


package main import (
"bytes"
"encoding/json"
"fmt"
"log"
"strconv"
"github.com/gin-gonic/gin"
) func main() {
engine := gin.Default() // GET请求 Query / DefaultQuery 单个接收get参数 //http://localhost:8080/hello?name=haima
engine.GET("/hello", func(context *gin.Context) {
fmt.Println(context.FullPath()) //获取字符串参数
username := context.Query("name") //方法一
fmt.Println(username)
//name := context.DefaultQuery("name", "") //方法二
//fmt.Println(name) context.Writer.Write([]byte("Hello," + username)) //Hello,go
}) type Student struct {
Name string `form:"name"`
Classes string `form:"classes"`
} // GET请求 ShouldBindQuery 批量接收get参数 // http://localhost:8080/hello2?name=davie&classes=软件工程
engine.GET("/hello2", func(context *gin.Context) {
fmt.Println(context.FullPath())
var student Student
err := context.ShouldBindQuery(&student)
if err != nil {
log.Fatal(err.Error())
} fmt.Println(student.Name) //davie
fmt.Println(student.Classes) //软件工程
context.Writer.Write([]byte("hello," + student.Name)) }) type Register struct {
UserName string `form:"name"`
Phone string `form:"phone"`
Password string `form:"pwd"`
} //http://localhost:8080/login
//单个接收post过来的参数
engine.POST("/login", func(context *gin.Context) { fmt.Println(context.FullPath()) // /login
username := context.PostForm("username") //方法一
//username, exist := context.GetPostForm("username") //方法二
userId, _ := strconv.ParseInt(context.Query("user_id"), 10, 64) //if !exist {
// fmt.Println(username) //adf
//} //password := context.PostForm("pwd")
password, exists := context.GetPostForm("pwd") //12323
//password:= com.StrTo(context.GetPostForm("pwd")).MustInt() if !exists {
fmt.Println(password) //12323
}
fmt.Printf("%T %s\n", username,username) //string adf
fmt.Printf("%T %d\n", userId,userId) //int64 0
fmt.Printf("%T %s\n", password,password) //string 12323
context.Writer.Write([]byte("Hello " + username + ", pwd:" + password)) //Hello go, pwd:123
}) //http://localhost:8080/register
// ShouldBind 批量接收post数据 application/x-www-form-urlencoded方式
engine.POST("/register", func(context *gin.Context) {
fmt.Println(context.FullPath())
var register Register
if err := context.ShouldBind(&register); err != nil {
log.Fatal(err.Error())
return
} fmt.Println(register.UserName)
fmt.Println(register.Phone)
context.Writer.Write([]byte(register.UserName + " Register ")) }) // POST multipart/form-data 方式
formData,err:=c.MultipartForm()
fmt.Println("++MultipartForm++",formData,err)
for k,v :=range formData.Value{
fmt.Println("k---->",k) #k----> name k----> age
fmt.Println("v---->",v[0]) #v----> haima v----> 30
} // BindJSON 批量接收 post raw json 数据 方法一 //http://localhost:8080/testpost
//{
// "user_id": 1,
// "linkbook_id": "001",
// "type":"education",
// "id": 2
//}
engine.POST("/testpost", func(ctx *gin.Context) {
fmt.Println(ctx.FullPath()) type delInfo struct {
UserID int `from:"user_id"`
LinkbookID string `from:"linkbook_id"`
Type string `from:"type"`
ID int `from:"id"`
}
var delInfoParam delInfo
if err := ctx.BindJSON(&delInfoParam); err != nil {
log.Fatal(err.Error())
return
} ctx.Writer.Write([]byte("Hello," + delInfoParam.Type)) //Hello,go
}) // BindJSON 批量接收 post raw json 数据 方法二 //http://localhost:8080/test
engine.POST("/test", func(context *gin.Context) {
fullPath := "请求路径:" + context.FullPath()
fmt.Println(fullPath)
SetBodyJson(context, "json")
var delInfo map[string]interface{}
err := getRequestBody(context, &delInfo)
fmt.Println(err)
fmt.Println(delInfo)
}) //http://localhost:8080/user/22
engine.DELETE("/user/:id", DeleteHandle) engine.Run(":8090")
} //http://localhost:8080/user/adf
func DeleteHandle(context *gin.Context) {
fmt.Println(context.FullPath()) // /user/:id userID := context.Param("id") fmt.Println(userID) //adf context.Writer.Write([]byte("Delete user's id : " + userID)) //Delete user's id : adf
} func getRequestBody(context *gin.Context, s interface{}) error {
body, _ := context.Get("json")
reqBody, _ := body.(string)
decoder := json.NewDecoder(bytes.NewReader([]byte(reqBody)))
decoder.UseNumber()
err := decoder.Decode(&s)
return err
} // @desc 通过上下文获取body内容并将内容写到指定key中
func SetBodyJson(context *gin.Context, key string) {
body := make([]byte, 1048576)
n, _ := context.Request.Body.Read(body)
fmt.Println("request body:", n)
context.Set(key, string(body[0:n]))
} //type People interface {
// name()
//}
//
//type Wang struct {
// Name string
//}
//
//func (p *Wang) name() {
// p.Name = "wang"
//}
//
//func (p *Wang) sayMyName() {
// fmt.Println(p.Name)
//}

context.Param获取请求参数

客户端的请求接口是DELETE类型,请求url为:http://localhost:9000/user/1。

最后的1是要删除的用户的id,是一个变量。因此在服务端gin中,

通过路由的:id来定义一个要删除用户的id变量值,

同时使用context.Param进行获取

gin框架获取参数的更多相关文章

  1. DRF框架获取参数的方式

    DRF获取参数的方式 例如url url(r'^demo/(?P<word>.*)/$', DemoView.as_view()) 在类视图中获取参数 url:http://127.0.0 ...

  2. Node.js中的express框架获取参数

    express获取参数有三种方法: req.query  适合 http://localhost:3000/form?num=8888 req.body   适合http://localhost:30 ...

  3. Gin框架body参数获取

    需求: 记录所有请求的json数据 body, _ := ioutil.ReadAll(c.Request.Body) if body != nil { log.Info("请求body内容 ...

  4. Gin框架之参数绑定

    为了能够更方便的获取请求相关参数,提高开发效率,我们可以基于请求的Content-Type识别请求数据类型并利用反射机制自动提取请求中QueryString.form表单.JSON.XML等参数到结构 ...

  5. Gin框架使用详解

    1.什么是Gin Gin是go编写的一个web应用框架. 2.Gin安装 go get github.com/gin-gonic/gin 3.Gin使用示例 package main import ( ...

  6. go的gin框架从请求中获取参数的方法

    前言: go语言的gin框架go里面比较好的一个web框架, github的start数超过了18000.可见此框架的可信度 如何获取请求中的参数 假如有这么一个请求: POST   /post/te ...

  7. Gin框架系列02:路由与参数

    回顾 上一节我们用Gin框架快速搭建了一个GET请求的接口,今天来学习路由和参数的获取. 请求动词 熟悉RESTful的同学应该知道,RESTful是网络应用程序的一种设计风格和开发方式,每一个URI ...

  8. Node.js中的express框架获取http参数

    最近本人在学习开发NodeJs,使用到express框架,对于网上的学习资料甚少,因此本人会经常在开发中做一些总结. express获取参数有三种方法:官网介绍如下 Checks route para ...

  9. Gin框架04:趣谈参数绑定与校验

    导读 在第二节,我们学习了Gin框架的路由定义与参数接收,今天应一位同学的要求,来讲解一下参数的绑定与校验. 为什么校验参数? 本不必抛出这个问题的,但顾及到初出茅庐的同学,这里解释一下. 假设做一个 ...

  10. gin框架中的参数验证

    结构体验证 用gin框架的数据验证,可以不用解析数据,减少if else,会简洁许多. 处理请求方法 func structValidator(context *gin.Context) { var ...

随机推荐

  1. C++设计模式 - 装饰器(Decorator)

    单一职责模式: 在软件组件的设计中,如果责任划分的不清晰,使用继承得到的结果往往是随着需求的变化,子类急剧膨胀,同时充斥着重复代码,这时候的关键是划清责任. 典型模式 Decorator Bridge ...

  2. #李超线段树 or 斜率优化+CDQ分治#洛谷 4655 [CEOI2017]Building Bridges

    题目 分析 列出方程即为\(dp[i]=\min\{dp[j]+(h[i]-h[j])^2+s[i-1]-s[j]\}\) \(dp[j]+h[j]^2-s[j]=2*h[i]*h[j]+dp[i]- ...

  3. #网络流,最小割#洛谷 1344 [USACO4.4]追查坏牛奶Pollutant Control

    题目 分析 考虑答案求的是最小割,但是最小割的最小边数有点难求, 考虑建立双关键字,其实就是将边权赋值为原边权\(*mx+1\), 其中\(mx\)是一个比较大的数,不需要太大, 这样用网络流做之后对 ...

  4. Go 语言中的 Switch 语句详解

    switch语句 使用switch语句来选择要执行的多个代码块中的一个. 在Go中的switch语句类似于C.C++.Java.JavaScript和PHP中的switch语句.不同之处在于它只执行匹 ...

  5. openGauss 2.1.0 闪回特性

    openGauss 2.1.0 闪回特性 openGauss 2.1.0 于 2021 年 9 月 30 日发布,是 openGauss 的一个 Preview 版本,该版本生命周期仅为半年.该版本的 ...

  6. 基于Traefik如何实现向后转发自动去掉前缀?

    前言 Traefik 是一个现代的 HTTP 反向代理和负载均衡器,使部署微服务变得容易. Traefik 可以与现有的多种基础设施组件(Docker.Swarm 模式.Kubernetes.Mara ...

  7. Unity-PC 端调用SpVoice语音 (文字转语音)

    第一步引用文件 在VS当中 点击项目->添加引用-> 搜索Microsoft Speech Objecet Library 然后选中前面的白色方块点击确定就行了 插入之后 你的引用库中会多 ...

  8. 4天带你上手HarmonyOS ArkUI开发——《HarmonyOS ArkUI入门训练营之健康生活实战》

     <HarmonyOS ArkUI入门训练营之健康饮食应用>是面向入门开发者打造的实战课程系列.特邀华为终端BG高级开发工程师作为本次训练营讲师,以健康饮食为例,开展技术教学及实战案例分享 ...

  9. Centos7、CentOS8、CentOS9 修改硬盘分区大小扩充root分区大小

    Centos7 修改硬盘分区大小,实现CentOS无损分区扩容 扩充root分区大小 安装了CentOS7 开发环境及软件后,发现root分区已经才剩下不到1G空间,难不成要干掉重装,OMG,NO! ...

  10. .NET开源强大、易于使用的缓存框架 - FusionCache

    前言 缓存在程序中扮演着提升性能.降低资源消耗.改善用户体验等重要角色,是构建高效.可伸缩.稳定的系统不可或缺的重要组成部分.今天大姚给大家分享一款.NET开源(基于MIT license).强大.易 ...