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的配置文件 ...
随机推荐
- KingbaseES索引坏块
错误信息产生: 下面的报错一般为有坏块的产生. test=# select max(create_time) from public.tbl_table where create_time>=' ...
- NOIP 2007 普及组
NOIP 2007 普及组(DONE) 注:本文不附原题,可上Luogu有题对照查询. 1.CPU:即中央处理器,由运算器+控制器+寄存器组成,不含主板(但CPU是装在主板上的). 2.二维表即常见的 ...
- Java封装xml格式参数请求第三方接口
Java封装xml格式参数请求第三方接口 1.引用包 import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers ...
- Ubuntu一键安装/卸载docker和docker compose,可指定版本或安装最新版本。
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 @ 目录 前言 一.docker是什么? 二.docker compose是什么? 三.安装步骤 1.Ubuntu安装脚本 2.生成脚 ...
- Mysql Order 排序的时候占用很长时间解决思路
MySQL中的连表查询(JOIN)在进行ORDER BY排序时可能会变得很慢,尤其是当处理大量数据时.以下是一些优化策略,可以帮助减少排序操作的时间: 索引优化: 确保参与排序的列上有索引.如果排序的 ...
- 3. Vector Spaces and Subspaces
3.1 Vector Spaces The space \(R^n\) consists of all colunm vectors \(v\) with n components. We can a ...
- GPT-3的训练一次成本约为140万美元
训练GPT模型的成本非常高昂,因为它需要大量的计算资源和时间.具体来说,GPT-3的训练成本约为140万美元,对于一些更大的LLM模型,训练成本介于200万美元至1200万美元之间.此外,OpenAI ...
- Python/Spring Cloud Alibaba开发--前端复习笔记(1)———— html5和css3.html基础
Python/Spring Cloud Alibaba开发–前端复习笔记(1)---- html5和css3.html基础 1)概述和基本结构 超文本标记语言.超文本指超链接,标记指的是标签. 基本结 ...
- Go 单元测试基本介绍
目录 一.单元测试基本介绍 1.1 什么是单元测试? 1.2 如何写好单元测试 1.3 单元测试的优点 1.4 单元测试的设计原则 二.Go语言测试 2.1 Go单元测试概要 2.2 Go单元测试基本 ...
- NodeJS安装cnpm
介绍: NPM(Node Package Manager):Node的包管理器. CNPM(Chinese CPM):中国的NPM(国内使用,网速较快). 配置步骤 用npm安装cnpm npm in ...