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() // 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"`
} // 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数据 from-data
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 ")) }) // 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里获取http请求过来的参数的更多相关文章

  1. Django怎么获取get请求里面的参数

    获取get请求里面参数的两种方法之三种写法一,当get网址是127.0.0.1:8000/info/?id=20&s_id=30这种类型的网址时 我们在urls的路由的urlpatterns里 ...

  2. SpringBoot实战(四)获取接口请求中的参数(@PathVariable,@RequestParam,@RequestBody)

    上一篇SpringBoot实战(二)Restful风格API接口中写了一个控制器,获取了前端请求的参数,现在我们就参数的获取与校验做一个介绍: 一:获取参数 SpringBoot提供的获取参数注解包括 ...

  3. JS 获取get请求方式的参数

    //获取页面中的参数    name值参数名称(例如:http://localhost:8099/index.aspx?id=10,name则指的是id)function GetQueryString ...

  4. 获取get请求后面的参数

    var str = "www.baidu.com?id=1&name=zhangsan"; var data = str.split("?"); con ...

  5. Servlet中获取POST请求的参数

    在servlet.filter等中获取POST请求的参数 form表单形式提交post方式,可以直接从 request 的 getParameterMap 方法中获取到参数 JSON形式提交post方 ...

  6. Spring MVC(三)控制器获取页面请求参数以及将控制器数据传递给页面和实现重定向的方式

    首先做好环境配置 在mvc.xml里进行配置 1.开启组件扫描 2.开启基于mvc的标注 3.配置试图处理器 <?xml version="1.0" encoding=&qu ...

  7. 路由传值及获取参数,路由跳转,路由检测,this.$route.query和this.$route.params接收参数,HttpGet请求拼接url参数

    配置动态路由参数id: routes: [ // 动态路径参数 以冒号开头 { path: '/user/:id', component: User } ] html路由跳转: <router- ...

  8. spring boot拦截器中获取request post请求中的参数

    最近有一个需要从拦截器中获取post请求的参数的需求,这里记录一下处理过程中出现的问题. 首先想到的就是request.getParameter(String )方法,但是这个方法只能在get请求中取 ...

  9. SpringBoot08 请求方式、参数获取注解、参数验证、前后台属性名不一致问题、自定义参数验证注解、BeanUtils的使用

    1 请求方式 在定义一个Rest接口时通常会利用GET.POST.PUT.DELETE来实现数据的增删改查:这几种方式有的需要传递参数,后台开发人员必须对接收到的参数进行参数验证来确保程序的健壮性 1 ...

  10. Servlet学习(二):ServletConfig获取参数;ServletContext应用:请求转发,参数获取,资源读取;类装载器读取文件

    转载:http://www.cnblogs.com/xdp-gacl/p/3763559.html 一.ServletConfig讲解 1.1.配置Servlet初始化参数 在Servlet的配置文件 ...

随机推荐

  1. java实战:多属性排序

    多属性排序的核心点就是对Arrays.sort()和Collections.sort()方法的Comparator进行重写 Arrays.sort()的三种用法 1.1.Arrays.sort(int ...

  2. QT 自定义插件问题 error: LNK2001: 无法解析的外部符号

    为了重复利用已有的代码,我使用自定义插件进行开发.当每个插件独立开发时没有遇到问题,但是当插件B引用了插件A时就会在编译时报错 error: LNK2001: 无法解析的外部符号. 例如,先定义一个插 ...

  3. 手写数字图片识别——DL 入门案例

    Deep Learning Demo of Primary 下面介绍一个入门案例,如何使用TensorFlow和Keras构建一个CNN模型进行手写数字识别,以及如何使用该模型对自己的图像进行预测.尽 ...

  4. 使用OHOS SDK构建googletest

    参照OHOS IDE和SDK的安装方法配置好开发环境. 从github下载源码. 执行如下命令: git clone --depth=1 https://github.com/google/googl ...

  5. MySQL基本手册

    MySQL配置文件 MySQL软件使用的配置文件名为my.ini,在安装目录下. MySQL常用配置参数: 1.default-character-set:客户端默认字符集. 2.character- ...

  6. 初学STM32 SDIO(一)

    1. SDIO协议简介 ​ SDIO全称是安全数字输入/输出接口 ,控制器对SD卡进行读写通信操作一般有两种通信接口可选,一种是SPI接口,另外一种就是SDIO接口. 多媒体卡(MMC).SD卡. S ...

  7. 定了!12支队伍进入HarmonyOS极客马拉松2023决赛

      12支队伍将在8月初,华为开发者大会(HDC.Togerther)上展开巅峰对决!

  8. Blocks(单调栈)

    题干中说每次选择一个大于k的数,还要选他左右两个数其中之一加上一,最后问你最长的每个数不小于K的子序列. 这些都是障眼法,其实就是问你最长的平均值大于或等于K的最长子序列,这样就明朗了. 接下来就是找 ...

  9. centos8 \CentOS 9 Stream rpm 安装mysql8.0.28

    centos8 rpm 安装mysql8.0.28 检查 检测系统是否自带安装 MySQL 命令如下: rpm -qa | grep mysql 如果如下存在已安装的包,就需要卸载 mysql80-c ...

  10. CentOS 6.5 ZIP、RAR文件压缩解压操作详解

    ============zip文件的操作================= zip -r data.zip data 解释:将data文件夹压缩成了data.zip格式.   unzip data.z ...