gin里获取http请求过来的参数
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(®ister); 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请求过来的参数的更多相关文章
- Django怎么获取get请求里面的参数
获取get请求里面参数的两种方法之三种写法一,当get网址是127.0.0.1:8000/info/?id=20&s_id=30这种类型的网址时 我们在urls的路由的urlpatterns里 ...
- SpringBoot实战(四)获取接口请求中的参数(@PathVariable,@RequestParam,@RequestBody)
上一篇SpringBoot实战(二)Restful风格API接口中写了一个控制器,获取了前端请求的参数,现在我们就参数的获取与校验做一个介绍: 一:获取参数 SpringBoot提供的获取参数注解包括 ...
- JS 获取get请求方式的参数
//获取页面中的参数 name值参数名称(例如:http://localhost:8099/index.aspx?id=10,name则指的是id)function GetQueryString ...
- 获取get请求后面的参数
var str = "www.baidu.com?id=1&name=zhangsan"; var data = str.split("?"); con ...
- Servlet中获取POST请求的参数
在servlet.filter等中获取POST请求的参数 form表单形式提交post方式,可以直接从 request 的 getParameterMap 方法中获取到参数 JSON形式提交post方 ...
- Spring MVC(三)控制器获取页面请求参数以及将控制器数据传递给页面和实现重定向的方式
首先做好环境配置 在mvc.xml里进行配置 1.开启组件扫描 2.开启基于mvc的标注 3.配置试图处理器 <?xml version="1.0" encoding=&qu ...
- 路由传值及获取参数,路由跳转,路由检测,this.$route.query和this.$route.params接收参数,HttpGet请求拼接url参数
配置动态路由参数id: routes: [ // 动态路径参数 以冒号开头 { path: '/user/:id', component: User } ] html路由跳转: <router- ...
- spring boot拦截器中获取request post请求中的参数
最近有一个需要从拦截器中获取post请求的参数的需求,这里记录一下处理过程中出现的问题. 首先想到的就是request.getParameter(String )方法,但是这个方法只能在get请求中取 ...
- SpringBoot08 请求方式、参数获取注解、参数验证、前后台属性名不一致问题、自定义参数验证注解、BeanUtils的使用
1 请求方式 在定义一个Rest接口时通常会利用GET.POST.PUT.DELETE来实现数据的增删改查:这几种方式有的需要传递参数,后台开发人员必须对接收到的参数进行参数验证来确保程序的健壮性 1 ...
- Servlet学习(二):ServletConfig获取参数;ServletContext应用:请求转发,参数获取,资源读取;类装载器读取文件
转载:http://www.cnblogs.com/xdp-gacl/p/3763559.html 一.ServletConfig讲解 1.1.配置Servlet初始化参数 在Servlet的配置文件 ...
随机推荐
- 一篇文章了解CI/CD管道全流程
从CI/CD过程开始,包含所有阶段并负责创建自动化和无缝的软件交付的一系列步骤称为CI/CD管道工作流.使用CI/CD管道,软件发布工件可以从代码提交阶段到测试.构建.部署和生产阶段在管道中移动和前进 ...
- #回滚莫队,链表#洛谷 6349 [PA2011] Kangaroos
题目传送门 分析 首先区间 \([l,r]\) 与 \([L,R]\) 相交当且仅当 \(l\leq R\) 且 \(L\leq r\)(其实就是完全覆盖或者有一端点在区间中) 而且坐标范围太大了,如 ...
- Python 简介和用途
什么是Python? Python是一种流行的编程语言,由Guido van Rossum创建,并于1991年发布. 它用于以下领域: 网页开发(服务器端) 软件开发 数学 系统脚本编写 Python ...
- 记录C++,base64解码写PDF文件遇到的坑
不得不bb一下, 场景:用户传base64数据,我生成PDF文件保存到指定路径下 背景:在前人写好的工程上增加这个功能,工程中有base64的.h, .cpp 文件,我试了base64编码没有问题,所 ...
- C++调用Python-0:搭建环境
1.进入到Python安装目录 2.将Python安装目录中的 include 和 libs 文件夹放在 C++项目中 3.设置 附加包含目录 和 附加库目录.附加依赖项(python310_d.li ...
- Python从 requirements.txt 安装库
pip install -r requirements.txt
- 什么是慢SQL且如何查看慢SQL
什么是慢 SQL 且如何查看慢 SQL? 介绍 某个 SQL 执行时间超过指定时间时称为慢 SQL.我们可以查看慢 SQL,包括历史慢 SQL 以及当前慢 SQL. 查看历史慢 SQL 首先要设置 l ...
- 敲重点!HarmonyOS这些更新将会影响原子化服务上架
原文:https://mp.weixin.qq.com/s/t-MaHqYiJ3z-QxaIsgWNPA,点击链接查看更多技术内容. 一.引言 随着原子化服务生态的发展,我们的业务诉求也在不断地变化, ...
- centos 6.4更新163源
centos 6.4更新163源 1. 备份现在的源文件 mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base. ...
- Android开发 Error:The number of method references in a .dex file cannot exceed 64K.Android开发 Error:The number of method references in a .dex file cannot exceed 64K
前言 错误起因: 在Android系统中,一个App的所有代码都在一个Dex文件里面. Dex是一个类似Jar的存储了多有Java编译字节码的归档文件. 因为Android系统使用Dalvik虚拟机, ...