HTTP Header 在线解析
访问 dhcp.cn/headeropen in new window 查看当前 HTTP Header
1. 通过 curl 命令模拟发送
1.1 GET 请求示例
curl dhcp.cn/header/shop
UserAgent: curl/7.64.1
Protocol: HTTP/1.1
Method: GET
Host: header.dhcp.cn
RemoteAddr: 192.168.31.125:56672
RequestURI: /header/shop
Header: map[Accept:[*/*] User-Agent:[curl/7.64.1]]
Body:
X-Forwarded-For:
Accept: */*
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
1.1 POST 请求示例
curl -XPOST -H 'X-Forwarded-For: 192.168.1.1' -H "content-Type: application/JSON" dhcp.cn/header/mall -d '{"age": 22}'
UserAgent: curl/7.64.1
Protocol: HTTP/1.1
Method: POST
Host: header.dhcp.cn
RemoteAddr: 192.168.31.125:56028
RequestURI: /header/mall
Header: map[Accept:[*/*] Content-Length:[11] Content-Type:[application/JSON] User-Agent:[curl/7.64.1] X-Forwarded-For:[192.168.1.1]]
Body: {"age": 22}
X-Forwarded-For: 192.168.1.1
Accept: */*
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
2. Golang 获取 HTTP Header
以下是一个完整的基于 Golang 实现的 HTTP Server,打印 HTTP Header。
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body) // 获取 Body,因为 r.Body 的类型是 io.ReadCloser,而不是 string
fmt.Fprintf(w, "UserAgent: %s\n", r.UserAgent()) // 示例:curl/7.64.1,r.UserAgent() 是字符串,直接打印即可
fmt.Fprintf(w, "Protocol: %s\n", r.Proto) // 示例:HTTP/1.1
fmt.Fprintf(w, "Method: %s\n", r.Method) // 示例:GET
fmt.Fprintf(w, "Host: %s\n", r.Host) // 示例:192.168.31.125,请求主机
fmt.Fprintf(w, "RemoteAddr: %s\n", r.RemoteAddr) // 示例:192.168.31.125:54642,客户端地址(如果用了负载均衡器,请通过 X-Forwarded-For 来获取客户端真实IP)
fmt.Fprintf(w, "RequestURI: %s\n", r.RequestURI) // 示例:/mall,请求URI
fmt.Fprintf(w, "Header: %s\n", r.Header) // 示例:map[Accept:[*/*] Content-Length:[11] Content-Type:[application/JSON] User-Agent:[curl/7.64.1] X-Forwarded-For:[192.168.1.1]]
fmt.Fprintf(w, "Body: %s\n", body) // 示例:{"age": 22},例如POST 请求的 Body
fmt.Fprintf(w, "X-Forwarded-For: %s\n", r.Header.Get("X-Forwarded-For")) // 示例:192.168.1.1,自定义Header,一般有负载均衡器的场景会把客户端的真实IP存储在这里
fmt.Fprintf(w, "Accept: %s\n", r.Header.Get("Accept")) // 示例:*/*
})
log.Println("Starting server ...")
log.Fatal(http.ListenAndServe(":80", nil))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31