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. KingbaseES V8R3数据库运维案例之---不完整的启动包(incomplete startup packet)复现

    案例说明: 在KingbaseES V8R3数据库的sys_log日志中,出现以下故障信息"不完整的启动包(incomplete startup packet)"日志信息.本案例复 ...

  2. 14 JavaScript神奇的windows

    14 神奇的windows window对象是一个很神奇的东西. 你可以把这东西理解成javascript的全局. 如果我们默认不用任何东西访问一个标识符. 那么默认认为是在用window对象. 例如 ...

  3. #线段树,约数#洛谷 3889 [GDOI2014]吃

    题目 有一个长度为\(n\)的数列,现在有\(m\)组询问每次给出区间\([l,r]\),查询 \[\max_{i,j=1}^n\{gcd(a_i,a_j)[(i<l或i>r)且l\leq ...

  4. K8s技术全景:架构、应用与优化

    本文深入探讨了Kubernetes(K8s)的关键方面,包括其架构.容器编排.网络与存储管理.安全与合规.高可用性.灾难恢复以及监控与日志系统. 关注[TechLeadCloud],分享互联网架构.云 ...

  5. 详讲openGauss 5.0 单点企业版如何部署_Centos7_x86

    本文分享自华为云社区<openGauss 5.0 单点企业版部署_Centos7_x86>,本文作者:董小姐 本文档环境:CentOS7.9 x86_64 4G1C40G python2. ...

  6. 新手的登录qsnctfwp

    打开登录界面 按要求以普通用户 user 的身份,通过密码 password 登录 使用 BurpSuite 拦截登录情况 在获取(GET)登录结果页面时,修改 Cookie 中的 username ...

  7. sql 语句系列(列举系列)[八百章之第八章]

    前言 这一张就是就是查询自己设计数据库的结构,对于接收一个老的项目相当重要. 列举模式中的表 查询所以表 select table_name from INFORMATION_SCHEMA.TABLE ...

  8. 升级gradle:Could not find method jackOptions() for arguments

    前言 这是我在升级gradle发生的错误. 解决 原因是被废弃了: 删除: jackOptions { enabled true } 解释一下什么是jack: Jack 是 Java Android ...

  9. spring boot properties 编码问题[四]

    情景 application.properties 中: server.port=8081 person.last-name=张三 person.age=18 person.birth=2017/12 ...

  10. c# 前台和后台线程

    前台和后台线程 Net的公用语言运行时(Common Language Runtime,CLR)能区分两种不同类型的线程:前台线程和后台线程.这两者的区别就是:应用程序必须运行完所有的前台线程才可以退 ...