字节赫兹 框架教程 一请求上下文之请求(二)

简介: 字节赫兹 框架教程 一请求上下文之请求

字节赫兹 框架教程 一请求上下文之请求(一)https://developer.aliyun.com/article/1391802

Header
// RequestHeader
func (h *RequestHeader) Add(key, value string)
func (h *RequestHeader) Set(key, value string)
func (h *RequestHeader) Header() []byte
func (h *RequestHeader) String() string
func (h *RequestHeader) VisitAll(f func(key, value []byte))
// RequestContext
func (ctx *RequestContext) IsGet() bool 
func (ctx *RequestContext) IsHead() bool
func (ctx *RequestContext) IsPost() bool
func (ctx *RequestContext) Method() []byte
func (ctx *RequestContext) ContentType() []byte
func (ctx *RequestContext) IfModifiedSince(lastModified time.Time) bool 
func (ctx *RequestContext) Cookie(key string) []byte
func (ctx *RequestContext) UserAgent() []byte
func (ctx *RequestContext) GetHeader(key string) []byte
Add

添加或设置键为 key 的 Header。

注意:Add 通常用于为同一个 Key 设置多个 Header,若要为同一个 Key 设置单个 Header 请使用 Set。当作用于 Content-Type, Content-Length, Connection, Cookie, Transfer-Encoding, Host, User-Agent 这些 Header 时,使用多个 Add 会覆盖掉旧值。

函数签名:

func (h *RequestHeader) Add(key, value string)

示例:

hertz.GET("/example", func(c context.Context, ctx *app.RequestContext) {
  ctx.Request.Header.Add("hertz1", "value1")
  ctx.Request.Header.Add("hertz1", "value2")
  ctx.Request.Header.SetContentTypeBytes([]byte("application/x-www-form-urlencoded"))
  contentType1 := ctx.Request.Header.ContentType() 
    // contentType1 == []byte("application/x-www-form-urlencoded")
  ctx.Request.Header.Add("Content-Type", "application/json; charset=utf-8")
  hertz1 := ctx.Request.Header.GetAll("hertz1") 
    // hertz1 == []string{"value1", "value2"}
  contentType2 := ctx.Request.Header.ContentType() 
    // contentType2 == []byte("application/json; charset=utf-8")
  })
Set

设置 Header 键值。

注意:Set 通常用于为同一个 Key 设置单个 Header,若要为同一个 Key 设置多个 Header 请使用 Add。

函数签名:

func (h *RequestHeader) Set(key, value string)

示例:

hertz.GET("/example", func(c context.Context, ctx *app.RequestContext) {
  ctx.Request.Header.Set("hertz1", "value1")
  ctx.Request.Header.Set("hertz1", "value2")
  ctx.Request.Header.SetContentTypeBytes([]byte("application/x-www-form-urlencoded"))
  contentType1 := ctx.Request.Header.ContentType() 
    // contentType1 == []byte("application/x-www-form-urlencoded")
  ctx.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  hertz1 := ctx.Request.Header.GetAll("hertz1")    
    // hertz1 == []string{"value2"}
  contentType2 := ctx.Request.Header.ContentType() 
    // contentType2 == []byte("application/json; charset=utf-8")
  })
Header

获取 []byte 类型的完整的 Header。

函数签名:

func (h *RequestHeader) Header() []byte

示例:

hertz.GET("/example", func(c context.Context, ctx *app.RequestContext) {
  ctx.Request.Header.Set("hertz1", "value1")
  ctx.Request.Header.Set("hertz1", "value2")
  ctx.Request.Header.SetContentTypeBytes([]byte("application/x-www-form-urlencoded"))
  contentType1 := ctx.Request.Header.ContentType() 
    // contentType1 == []byte("application/x-www-form-urlencoded")
  ctx.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  hertz1 := ctx.Request.Header.GetAll("hertz1")    
    // hertz1 == []string{"value2"}
  contentType2 := ctx.Request.Header.ContentType() 
    // contentType2 == []byte("application/json; charset=utf-8")
  })
String

获取完整的 Header。

函数签名:

func (h *RequestHeader) String() string

示例:

hertz.GET("/example", func(c context.Context, ctx *app.RequestContext) {
    ctx.Request.Header.Set("hertz1", "value1")
    header := ctx.Request.Header.String()
    // header == "GET /example HTTP/1.1
    //User-Agent: PostmanRuntime-ApipostRuntime/1.1.0
    //Host: localhost:8888
    //Cache-Control: no-cache
    //Accept: */*
    //Accept-Encoding: gzip, deflate, br
    //Connection: keep-alive
    //Hertz1: value1"
  })
遍历 Header

遍历所有 Header 的键值并执行 f 函数。

函数签名:

func (h *RequestHeader) VisitAll(f func(key, value []byte))

示例:

hertz.GET("/example", func(c context.Context, ctx *app.RequestContext) {
  ctx.Request.Header.Add("Hertz1", "value1")
  ctx.Request.Header.Add("Hertz1", "value2")
  var hertzString []string
  ctx.Request.Header.VisitAll(func(key, value []byte) {
    if string(key) == "Hertz1" {
      hertzString = append(hertzString, string(value))
    }
  })
  // hertzString == []string{"value1", "value2"}
  })
ethod

获取请求方法的类型。

函数签名:

func (ctx *RequestContext) Method() []byte

示例:

// POST http://example.com/user
h.Any("/user", func(c context.Context, ctx *app.RequestContext) {
    method := ctx.Method() // method == []byte("POST")
})
ContentType

获取请求头 Content-Type 的值。

函数签名:

func (ctx *RequestContext) ContentType() []byte

示例:

// POST http://example.com/user
// Content-Type: application/json
h.Post("/user", func(c context.Context, ctx *app.RequestContext) {
    contentType := ctx.ContentType() // contentType == []byte("application/json")
})
IfModifiedSince

判断时间是否超过请求头 If-Modified-Since 的值。

注意:如果请求头不包含 If-Modified-Since 也返回 true。

函数签名:

func (ctx *RequestContext) IfModifiedSince(lastModified time.Time) bool

示例:

// POST http://example.com/user
// If-Modified-Since: Wed, 21 Oct 2023 07:28:00 GMT
h.Post("/user", func(c context.Context, ctx *app.RequestContext) {
    t2022, _ := time.Parse(time.RFC1123, "Wed, 21 Oct 2022 07:28:00 GMT")
    ifModifiedSince := ctx.IfModifiedSince(t2022) // ifModifiedSince == false
    t2024, _ := time.Parse(time.RFC1123, "Wed, 21 Oct 2024 07:28:00 GMT")
    ifModifiedSince = ctx.IfModifiedSince(t2024) // ifModifiedSince == true
})
Cookie

获取请求头 Cookie 中 key 的值。

函数签名:

func (ctx *RequestContext) Cookie(key string) []byte

示例:

// POST http://example.com/user
// Cookie: foo_cookie=choco; bar_cookie=strawberry
h.Post("/user", func(c context.Context, ctx *app.RequestContext) {
    fCookie := ctx.Cookie("foo_cookie")     // fCookie == []byte("choco")
    bCookie := ctx.Cookie("bar_cookie")     // bCookie == []byte("strawberry")
    noneCookie := ctx.Cookie("none_cookie") // noneCookie == nil
})
UserAgent

获取请求头 User-Agent 的值。

函数签名:

func (ctx *RequestContext) UserAgent() []byte

示例:

// POST http://example.com/user
// User-Agent: Chrome/51.0.2704.103 Safari/537.36
h.Post("/user", func(c context.Context, ctx *app.RequestContext) {
    ua := ctx.UserAgent() // ua == []byte("Chrome/51.0.2704.103 Safari/537.36")
})
GetHeader

获取请求头中 key 的值。

函数签名:

func (ctx *RequestContext) GetHeader(key string) []byte

示例:

// POST http://example.com/user
// Say-Hello: hello
h.Post("/user", func(c context.Context, ctx *app.RequestContext) {
    customHeader := ctx.GetHeader("Say-Hello") // customHeader == []byte("hello")
})
Body
func (ctx *RequestContext) GetRawData() []byte
func (ctx *RequestContext) Body() ([]byte, error) 
func (ctx *RequestContext) RequestBodyStream() io.Reader
func (ctx *RequestContext) MultipartForm() (*multipart.Form, error)
func (ctx *RequestContext) PostForm(key string) string
func (ctx *RequestContext) DefaultPostForm(key, defaultValue string) string 
func (ctx *RequestContext) GetPostForm(key string) (string, bool) 
func (ctx *RequestContext) PostArgs() *protocol.Args
func (ctx *RequestContext) FormValue(key string) []byte 
func (ctx *RequestContext) SetFormValueFunc(f FormValueFunc)
Body

获取请求的 body 数据,如果发生错误返回 error。

函数签名:

func (ctx *RequestContext) Body() ([]byte, error) 

示例:

// POST http://example.com/pet
// Content-Type: application/json
// {"pet":"cat"}
h.Post("/pet", func(c context.Context, ctx *app.RequestContext) {
    data, err := ctx.Body() // data == []byte("{\"pet\":\"cat\"}") , err == nil
})
RequestBodyStream

获取请求的 BodyStream。

函数签名:

func (ctx *RequestContext) RequestBodyStream() io.Reader

示例:

// POST http://example.com/user
// Content-Type: text/plain
// abcdefg
h := server.Default(server.WithStreamBody(true))
h.Post("/user", func(c context.Context, ctx *app.RequestContext) {
    sr := ctx.RequestBodyStream()
    data, _ := io.ReadAll(sr) // data == []byte("abcdefg")
})
MultipartForm

获取 multipart.Form 对象,(详情请参考 multipart#Form)

注意:此函数既可以获取普通值也可以获取文件,此处给出了获取普通值的示例代码,获取文件的示例代码可参考 MultipartForm。

函数签名:

func (ctx *RequestContext) MultipartForm() (*multipart.Form, error)

示例:

// POST http://example.com/user
// Content-Type: multipart/form-data; 
// Content-Disposition: form-data; name="name"
// tom
h.POST("/user", func(c context.Context, ctx *app.RequestContext) {
    form, err := ctx.MultipartForm()
    name := form.Value["name"][0] // name == "tom"
})
PostForm

按名称检索 multipart.Form.Value,返回给定 name 的第一个值。

注意:该函数支持从 application/x-www-form-urlencoded 和 multipart/form-data 这两种类型的 content-type 中获取 value 值,且不支持获取文件值。

函数签名:

func (ctx *RequestContext) PostForm(key string) string

示例:

// POST http://example.com/user
// Content-Type: multipart/form-data; 
// Content-Disposition: form-data; name="name"
// tom
h.POST("/user", func(c context.Context, ctx *app.RequestContext) {
    name := ctx.PostForm("name") // name == "tom"
})
DefaultPostForm

按名称检索 multipart.Form.Value,返回给定 name 的第一个值,如果不存在返回 defaultValue。

注意:该函数支持从 application/x-www-form-urlencoded 和 multipart/form-data 这两种类型的 content-type 中获取 value 值,且不支持获取文件值。

函数签名:

func (ctx *RequestContext) DefaultPostForm(key, defaultValue string) string 

示例:

// POST http://example.com/user
// Content-Type: multipart/form-data; 
// Content-Disposition: form-data; name="name"
// tom
h.POST("/user", func(c context.Context, ctx *app.RequestContext) {
    name := ctx.PostForm("name", "jack") // name == "tom"
    age := ctx.PostForm("age", "10") // age == "10"
})
PostArgs

获取 application/x-www-form-urlencoded 参数对象。(详情请参考 Args 对象)

函数签名:

func (ctx *RequestContext) PostArgs() *protocol.Args

示例:

// POST http://example.com/user
// Content-Type: application/x-www-form-urlencoded
// name=tom&pet=cat&pet=dog
h.POST("/user", func(c context.Context, ctx *app.RequestContext) {
    args := ctx.PostArgs()
    name := args.Peek("name") // name == "tom"
    var pets []string
    args.VisitAll(func(key, value []byte) {
        if string(key) == "pet" {
        pets = append(pets, string(value))
        }
    })
    // pets == []string{"cat", "dog"}
})


字节赫兹 框架教程 一请求上下文之请求(三)https://developer.aliyun.com/article/1391804

相关文章
|
3天前
|
安全 中间件
字节赫兹 框架教程 一请求上下文之请求(三)
字节赫兹 框架教程 一请求上下文之请求
47 0
|
8月前
|
监控 前端开发 网络协议
GB/T 28181-2016多响应消息传输探究
我们在实现Android平台GB28181设备接入模块的时候,有遇到发送多条记录的情况,本文主要探讨下GB28181多响应传输。
|
3天前
|
数据采集 搜索推荐 API
python爬虫如何处理请求频率限制?
【2月更文挑战第21天】【2月更文挑战第64篇】python爬虫如何处理请求频率限制?
|
3天前
|
存储 安全 中间件
字节赫兹 框架教程 一请求上下文之请求(一)
字节赫兹 框架教程 一请求上下文之请求
25 0
|
6月前
|
监控 流计算
Flink 指标参数源码解读(读取数量、发送数量、发送字节数、接收字节数等)(上)
Flink 指标参数源码解读(读取数量、发送数量、发送字节数、接收字节数等)(上)
60 1
|
存储 算法
【实测】大白话讲requests发送请求的不同参数类型(上)
【实测】大白话讲requests发送请求的不同参数类型(上)
|
XML JSON 前端开发
【实测】大白话讲requests发送请求的不同参数类型(下)
【实测】大白话讲requests发送请求的不同参数类型(下)
|
BI 索引
HID 入门学习:标准请求和类请求
HID 入门学习:标准请求和类请求
198 0
|
传感器
十四、差错控制(检错编码)
十四、差错控制(检错编码)
十四、差错控制(检错编码)
|
应用服务中间件
设置请求编码
设置编码,改成我们习惯的中文输出