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")
}
}
评论