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

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

字节赫兹 框架教程 一请求上下文之请求(一)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

相关文章
|
JSON 缓存 Go
Golang 语言 Web 框架 beego v2 之控制器方法和输入输出数据
Golang 语言 Web 框架 beego v2 之控制器方法和输入输出数据
224 0
|
1月前
|
数据挖掘 调度 开发工具
Github 2.3k star 太牛x,京东(JoyAgent‑JDGenie)这个开源项目来得太及时啦,端到端多智能体神器!!!
JoyAgent-JDGenie是京东开源的端到端产品级多智能体系统,支持自然语言生成报告、PPT、网页等内容,准确率达75.15%。具备开箱即用、多智能体协同、高扩展性及跨任务记忆能力,支持多种文件格式输出,部署灵活,不依赖私有云平台。适合企业自动化报告生成、数据分析与行业定制化应用,是高效、实用的开源AI工具。
333 0
|
2月前
|
存储 人工智能 自然语言处理
无影AgentBay来了!给AI智能体装上“超级大脑”
阿里云在WAIC上发布专为AI Agents打造的“超级大脑”——无影AgentBay。该云端电脑支持多系统切换,集成视觉理解、自然语言控制等多项AI能力,提供高性能算力与企业级安全保障,助力AI开发者高效构建智能应用。
183 0
无影AgentBay来了!给AI智能体装上“超级大脑”
|
10月前
|
存储 人工智能 对象存储
一文详解阿里云AI大基建
一文详解阿里云AI大基建
1531 2
|
Ubuntu 网络协议 Linux
如何白piao一个免费的泛域名SSL证书
为了给个人博客提速,全部静态资源放到云上的对象存储中,并且加了CDN,耗费了不少RMB。新申请的域名也备案通过了,但是SSL证书一般需要按年付款,看了下「鹅云」上最便宜的泛域名证书也裤头一紧
5899 0
如何白piao一个免费的泛域名SSL证书
|
Java API 数据库
FastAPI中如何调用同步函数
FastAPI中如何调用同步函数
582 0
Hertz踩坑记录,Hertz-CORS跨域问题
字节跳动开源框架Hertz,可能存在的CORS的跨域问题
|
安全 5G 网络安全
gRPC(五)进阶:通过TLS建立安全连接
发生会话密钥交换。在此过程中,客户端和服务器必须就密钥达成一致,以建立安全会话确实在客户端和服务器之间的事实——而不是在中间试图劫持会话的东西。
2142 1
gRPC(五)进阶:通过TLS建立安全连接
|
应用服务中间件 nginx
Nginx隐藏版本号
修改nginx.conf配置文件 nginx配置文件里增加 server_tokens off;server_tokens作用域是http server location语句块server_tokens默认值是on,表示显示版本信息,设置server_tokens值是off,就可以在所有地方隐藏nginx的版本信息。
5561 0