This topic created in 1141 days ago, the information mentioned may be changed or developed.
在使用 go "net/http" 创建一个 http.Request 去上传文件到 minio 的过程中, 发现了几个疑问点:
- 为什么 Header 是一个 map[string][]string, 虽然我看了网上一些讨论
https://www.reddit.com/r/golang/comments/cgbkel/why_are_headers_mapstringstring/
但也不太理解,
- Header 的 Add 跟 Set 的实际使用场景上的区别是? 为什么 Header 的值是个切片, 但 Get 却只返回第一个元素,
- 基于 2, 在实际使用过程中, 应该如何读取 Header 的值, 是遍历 Header 后使用键去 Get 还是直接使用值, 我觉得类型 Header 是非私有的会造成使用上的疑惑(・∀・(・∀・(・∀・*), 这是 go 的语法特点导致的么?
5 replies • 2023-05-09 09:22:48 +08:00
 |
|
1
aladdinding May 8, 2023
因为 http header 可以重复多次 比如 cookie
|
 |
|
2
FinnBai May 8, 2023 2
1. 因为 http header 就是设计成了这样的结构,值可以是数组。但并不代表所有 header 的值都必须支持数组配置,有些 header key 设计出来就只有一个字符串值 2. 基于上述设计理念,go header 结构体的辅助方法就很好理解了,Add 的场景就是为了给数组型 value 使用的,Set 是给字符串型 value 使用的,Get 也是 3. 在实际使用过程中,需要使用者明白当前你想使用的 header key 支持什么类型的 value ,假如是数组,那么就遍历,假如是字符串,那么直接用辅助方法 Get 就好
|
 |
|
3
darksword21 May 8, 2023
Add:添加新 header Set:设置现有 header 的 value
|
 |
|
4
hzzhzzdogee May 8, 2023
Add adds the key, value pair to the header. It appends to any existing values associated with key. Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key.
|