本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名原文链接~~~

beego笔记(3)之获取请求参数

微信搜索 zze_coding 或扫描 👉 二维码关注我的微信公众号获取更多资源推送:


此系列我仅会记录一些 Beego 的基本使用以及常用语法,而不会对每个知识点详述,尽量做到以注释的形式让有 Web 开发经验的小伙伴一看就懂,也让自己在以后忘了某个语法或知识点的时候看到这里能迅速找回感觉~

package main

import (
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/server/web"
	"io"
	"net/http"
	"os"
	"time"
)

type Demo1Controller struct {
	web.Controller
}

// 不常用,手动执行 ParseForm 解析参数到 c.Ctx.Request.Form
func (c *Demo1Controller) ReqParseFormTest() {
	c.Ctx.Request.ParseForm()
	// 还可通过 c.Ctx.Request.PostForm 仅获取 Post 请求 Body 中的参数
	fmt.Println(c.Ctx.Request.Form)
	c.Ctx.WriteString("c.Ctx.Request.Form")
	/*
		请求:
			POST /demo1/parseformtest/?name=zze1 HTTP/1.1
			Content-Type: application/x-www-form-urlencoded; charset=utf-8
			Host: 127.0.0.1:8080
			Connection: close
			User-Agent: Paw/3.2.2 (Macintosh; OS X/11.4.0) GCDHTTPRequest
			Content-Length: 6

			age=12
		响应:
			c.Ctx.Request.Form
		控制台输出:
			map[age:[12] name:[zze1]]
	*/
}

func (c *Demo1Controller) QueryTest() {
	name := c.Ctx.Input.Query("name")
	age := c.Ctx.Input.Query("age")
	c.Ctx.WriteString(fmt.Sprintf("c.Ctx.Input.Query(), name: %s, age: %s", name, age))
	/*
		请求:
			POST /demo1/querytest/?name=zze1 HTTP/1.1
			Content-Type: application/x-www-form-urlencoded; charset=utf-8
			Host: 127.0.0.1:8080
			Connection: close
			User-Agent: Paw/3.2.2 (Macintosh; OS X/11.4.0) GCDHTTPRequest
			Content-Length: 6

			age=12
		响应:
			c.Ctx.Input.Query(), name: zze1, age: 12
	*/
}

// 不常用
func (c *Demo1Controller) BindTest() {
	var name, age string
	c.Ctx.Input.Bind(&name, "name")
	c.Ctx.Input.Bind(&age, "name")
	c.Ctx.WriteString(fmt.Sprintf("c.Ctx.Input.Bind(), name: %s, age: %s", name, age))
	/*
		请求:
			POST /demo1/bindtest/?name=zze1 HTTP/1.1
			Content-Type: application/x-www-form-urlencoded; charset=utf-8
			Host: 127.0.0.1:8080
			Connection: close
			User-Agent: Paw/3.2.2 (Macintosh; OS X/11.4.0) GCDHTTPRequest
			Content-Length: 6

			age=12
		响应:
			c.Ctx.Input.Bind(), name: zze1, age: zze1
	*/
}

// Beego 提供了一些快捷函数快速获取请求参数并自动进行类型转换
func (c *Demo1Controller) GetXXXTest() {
	/*
		GetString(key string, def ...string) string
		GetStrings(key string, def ...[]string) []string
		GetInt(key string, def ...int) (int, error)
		GetInt8(key string, def ...int8) (int8, error)
		GetUint8(key string, def ...uint8) (uint8, error)
		GetInt16(key string, def ...int16) (int16, error)
		GetUint16(key string, def ...uint16) (uint16, error)
		GetInt32(key string, def ...int32) (int32, error)
		GetUint32(key string, def ...uint32) (uint32, error)
		GetInt64(key string, def ...int64) (int64, error)
		GetUint64(key string, def ...uint64) (uint64, error)
		GetBool(key string, def ...bool) (bool, error)
		GetFloat(key string, def ...float64) (float64, error)
		GetFile(key string) (multipart.File, *multipart.FileHeader, error)
		GetFiles(key string) ([]*multipart.FileHeader, error)
	*/
	// 方法签名如上,这里仅简单演示 GetString 和 GetInt
	name := c.GetString("name")
	age, err := c.GetInt("age")
	if err != nil {
		panic(err)
	}
	c.Ctx.WriteString(fmt.Sprintf("c.GetXXX(), name: %s, age %d", name, age))
	/*
		请求:
			POST /demo1/getxxxtest/?name=zze1 HTTP/1.1
			Content-Type: application/x-www-form-urlencoded; charset=utf-8
			Host: 127.0.0.1:8080
			Connection: close
			User-Agent: Paw/3.2.2 (Macintosh; OS X/11.4.0) GCDHTTPRequest
			Content-Length: 6

			age=12
		响应:
			c.GetXXX(), name: zze1, age 12
	*/
}

// 默认情况下请求参数的名称必须和结构体属性名称完全一致(区分大小写),如果希望手动映射请求参数和结构体属性之间的关系,可以通过 tag 额外指定
type ParamForm struct {
	Name string `form:"name"`
	Age  int    `form:"age"`
}

// 将请求参数封装到结构体中
func (c *Demo1Controller) ParseFormTest() {
	var form ParamForm
	c.ParseForm(&form)
	fmt.Printf("%#v", form)
	c.Ctx.WriteString("c.ParseForm()")

	/*
		请求:
			POST /demo1/parseformtest/?name=zze1 HTTP/1.1
			Content-Type: application/x-www-form-urlencoded; charset=utf-8
			Host: 127.0.0.1:8080
			Connection: close
			User-Agent: Paw/3.2.2 (Macintosh; OS X/11.4.0) GCDHTTPRequest
			Content-Length: 6

			age=12
		响应:
			c.ParseForm()
		控制台输出:
			main.ParamForm{Name:"zze1", Age:12}
	*/
}

// 此种方式其实就是对上述 ReqParseFormTest() 方式的一种封装 ,在 c.Input() 方法内执行了 c.Ctx.Request.ParseForm() 然后返回了 c.Ctx.Request.Form
func (c *Demo1Controller) InputTest() {
	formVals, err := c.Input()
	if err != nil {
		panic(err)
	}
	fmt.Printf("%#v\n", formVals)
	c.Ctx.WriteString("c.Input()")
	/*
		请求:
			POST /demo1/inputtest/?name=zze1 HTTP/1.1
			Content-Type: application/x-www-form-urlencoded; charset=utf-8
			Host: 127.0.0.1:8080
			Connection: close
			User-Agent: Paw/3.2.2 (Macintosh; OS X/11.4.0) GCDHTTPRequest
			Content-Length: 6

			age=12
		响应:
			c.Input()
		控制台输出:
			url.Values{"age":[]string{"12"}, "name":[]string{"zze1"}}
	*/
}

// 上传文件,此种方式是先根据文件参数名获取一个原始 multipart.File,然后针对 multipart.File 手动保存文件
func (c *Demo1Controller) GetFileTest() {
	file, header, err := c.GetFile("file")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()
	fmt.Printf("%#v", header)
	f, err := os.OpenFile("./upload/"+header.Filename, os.O_WRONLY|os.O_CREATE, 0666) // 此处假设当前目录下已存在upload目录
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()
	io.Copy(f, file)
	c.Ctx.WriteString("upload file ok...")
}

// 上传文件,直接调用 beego 提供的函数保存文件到指定位置
func (c *Demo1Controller) SaveToFileTest() {
	err := c.SaveToFile("file", "./upload/test.sql")
	if err != nil {
		panic(err)
	}
	c.Ctx.WriteString("upload file ok...")
}

// 获取原始请求 Body 内容
func (c *Demo1Controller) RequestBodyTest() {
	// 从请求 Body 中拷贝 10MB 数据到内存,通过 c.Ctx.Input.RequestBody
	c.Ctx.Input.CopyBody(10 * 1024 * 1024)
	var m map[string]interface{}
	body := c.Ctx.Input.RequestBody
	fmt.Printf("%#v\n", body)
	fmt.Printf("%#v\n", string(body))
	json.Unmarshal(body, &m)
	fmt.Printf("%#v\n", m)
	c.Ctx.WriteString("c.Ctx.Input.RequestBody")

	/*
		请求:
			POST /demo1/requestbodytest/?name=zze1 HTTP/1.1
			Content-Type: text/plain; charset=utf-8
			Host: 127.0.0.1:8080
			Connection: close
			User-Agent: Paw/3.2.2 (Macintosh; OS X/11.4.0) GCDHTTPRequest
			Content-Length: 13

			{"a":1,"b":2}
		响应:
			c.Ctx.Input.RequestBody
		控制台输出:
			[]byte{0x7b, 0x22, 0x61, 0x22, 0x3a, 0x31, 0x2c, 0x22, 0x62, 0x22, 0x3a, 0x32, 0x7d}
			"{\"a\":1,\"b\":2}"
			map[string]interface {}{"a":1, "b":2}
	*/
}

// Cookie 的获取与设置
func (c *Demo1Controller) GetCookieTest() {
	// -- Cookie 的获取 --
	// 方式一
	cookie1, err := c.Ctx.Request.Cookie("key1")
	if err == nil {
		fmt.Println(cookie1)
	}
	// 方式二
	cookie2 := c.Ctx.Input.Cookie("key2")
	fmt.Println(cookie2)
	// 方式三
	cookie3 := c.Ctx.GetCookie("key3")
	fmt.Println(cookie3)
	// -- Cookie 的设置 --
	// 方式一
	COOKIE_MAX_MAX_AGE := time.Hour * 24 / time.Second // 单位:秒。
	maxAge := int(COOKIE_MAX_MAX_AGE)

	uid_cookie := &http.Cookie{
		Name:     "key1",
		Value:    "c1",
		Path:     "/",
		HttpOnly: false,
		MaxAge:   maxAge,
	}

	http.SetCookie(c.Ctx.ResponseWriter, uid_cookie)
	// 方式二
	c.Ctx.SetCookie("key2", "c2")
	// -- 设置和获取安全的 Cookie  --
	key := "xxxxxx"
	c.Ctx.SetSecureCookie(key,"k1","v1")
	cookieVal, ok := c.Ctx.GetSecureCookie(key, "k1")
	if ok {
		fmt.Println(cookieVal)
	}
	c.Ctx.WriteString("ok")
}

func main() {
	web.AutoRouter(&Demo1Controller{})
	web.Run()
}

# Beego  

如果这篇文章对您有帮助,可点击下方链接分享给你的朋友们😋,如果遇到问题欢迎评论、留言~~~😇

评论

公众号:zze_coding

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×