目錄
獲取header頭里的參數:
scene := httpext.GetHeaderByName(ctx, "scene") // online / dev
// @desc 通過上下文獲取header中指定key的內容
func GetHeaderByName(ctx *gin.Context, key string) string {
return ctx.Request.Header.Get(key)
}
//獲取用戶微信信息表里的數據
body, _ := ctx.Get("json")
us.UserWxModel.WxUserInfo = service.BuildNick(body.(string)) /*編碼特殊特號*/
httpext包
package httpext
import (
"fmt"
"github.com/gin-gonic/gin"
"io/ioutil"
"linkbook.com/LinkBookGo/lib/apilog"
)
// @desc 通過上下文獲取header中指定key的內容
func GetHeaderByName(ctx *gin.Context, key string) string {
return ctx.Request.Header.Get(key)
}
// @desc 通過上下文獲取body內容並將內容寫到指定key中
func SetBodyJson(context *gin.Context, key string) {
body, _ := ioutil.ReadAll(context.Request.Body)
apilog.DebugLog("當前請求數據內容:", string(body[:]))
fmt.Println("當前請求的數據:", string(body[:]))
context.Set(key, string(body[:]))
}
方法二:
~~~
//獲取body里的數據
func getBodyData(c *server.Context) string {
var bodyBytes []byte
if c.Request.Body != nil {
bodyBytes, _ = ioutil.ReadAll(c.Request.Body)
}
// 把剛剛讀出來的再寫進去
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
return string(bodyBytes)
}
~~~
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()
// GET請求 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"`
}
// GET請求 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數據 application/x-www-form-urlencoded方式
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 "))
})
// POST multipart/form-data 方式
formData,err:=c.MultipartForm()
fmt.Println("++MultipartForm++",formData,err)
for k,v :=range formData.Value{
fmt.Println("k---->",k) #k----> name k----> age
fmt.Println("v---->",v[0]) #v----> haima v----> 30
}
// 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進行獲取