gin post 数据参数_gin里获取http请求过来的参数

本文展示了如何在Gin框架中获取GET和POST请求的参数。通过`context.Query`、`context.DefaultQuery`、`context.PostForm`、`context.GetPostForm`以及`context.ShouldBindQuery`和`context.ShouldBind`方法可以方便地获取单个或批量参数。示例包括从URL查询字符串、POST表单数据和JSON体中提取数据。
摘要由CSDN通过智能技术生成

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获取请求参数

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

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

同时使用context.Param进行获取

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值