编写一个 HTTP 服务器:
- 接收客户端 request,并将 request 中带的 header 写入 response header
- 读取当前系统的环境变量中的 VERSION 配置,并写入 response header
- Server 端记录访问日志包括客户端 IP,HTTP 返回码,输出到 server 端的标准输出
- 当访问 localhost/healthz 时,应返回 200
package main import ( "fmt" "log" "net/http" "os" ) func ReadUserIP(r *http.Request) string { IpAddress := r.Header.Get("X-Real-Ip") if IpAddress == "" { IpAddress = r.Header.Get("X-Forwarded-For") } if IpAddress == "" { IpAddress = r.RemoteAddr } return IpAddress } func health(w http.ResponseWriter, r *http.Request) { w.Write([]byte("working")) } func analyseHeader(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, this is server")) err := os.Setenv("VERSION", "V1.0.0") if err != nil { log.Fatalf("Setting env VERSION failed") } version := os.Getenv("VERSION") w.Header().Set("VERSION", version) fmt.Printf("os version: %s \n", version) // 将request中的header依次copy到response中 for k, v := range r.Header { for _, vv := range v { fmt.Printf("Header key: %s, Header value: %s \n", k, v) w.Header().Set(k, vv) } } fmt.Println(r.RemoteAddr) fmt.Printf("Ip is: %s\n", ReadUserIP(r)) log.Printf("Success! Response code: %d", 200) } func main() { serveMux := http.NewServeMux() serveMux.HandleFunc("/", analyseHeader) serveMux.HandleFunc("/healthz", health) err := http.ListenAndServe(":8080", serveMux) if err == nil { log.Fatalf("Starting server failed on port 8080 failed") } }