-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpserver2.go
100 lines (90 loc) · 2.79 KB
/
httpserver2.go
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"fmt"
"gocamp/metrics"
"io"
"log"
"math/rand"
"net"
"net/http"
"net/http/pprof"
"os"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func index(w http.ResponseWriter, r *http.Request) {
// w.Write([]byte("<h1>Welcome to Cloud Native</h1>"))
// 03.设置version os.Setenv("VERSION", "v0.0.1")
version := os.Getenv("VERSION")
w.Header().Set("VERSION", version)
fmt.Printf("os version: %s \n", version)
// 02.将requst中的header 设置到 reponse中
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)
}
io.WriteString(w, fmt.Sprintf("%s=%s\n", k, v))
}
// 04.记录日志并输出
clientip := getCurrentIP(r)
//fmt.Println(r.RemoteAddr)
log.Printf("Success! Response code: %d", 200)
log.Printf("Success! clientip: %s", clientip)
}
}
// 05.健康检查的路由
func healthz(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "200")
}
func getCurrentIP(r *http.Request) string {
// 这里也可以通过X-Forwarded-For请求头的第一个值作为用户的ip
// 但是要注意的是这两个请求头代表的ip都有可能是伪造的
ip := r.Header.Get("X-Real-IP")
if ip == "" {
// 当请求头不存在即不存在代理时直接获取ip
ip = strings.Split(r.RemoteAddr, ":")[0]
}
return ip
}
// ClientIP 尽最大努力实现获取客户端 IP 的算法。
// 解析 X-Real-IP 和 X-Forwarded-For 以便于反向代理(nginx 或 haproxy)可以正常工作。
func ClientIP(r *http.Request) string {
xForwardedFor := r.Header.Get("X-Forwarded-For")
ip := strings.TrimSpace(strings.Split(xForwardedFor, ",")[0])
if ip != "" {
return ip
}
ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
if ip != "" {
return ip
}
if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
return ip
}
return ""
}
func images(w http.ResponseWriter, r *http.Request) {
timer := metrics.NewTimer()
defer timer.ObserveTotal()
randInt := rand.Intn(2000)
time.Sleep(time.Millisecond * time.Duration(randInt))
w.Write([]byte(fmt.Sprintf("<h1>%d<h1>", randInt)))
}
func main() {
metrics.Register()
mux := http.NewServeMux()
// 06. debug mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
mux.HandleFunc("/", index)
mux.HandleFunc("/images", images)
mux.HandleFunc("/healthz", healthz)
mux.Handle("/metrics", promhttp.Handler())
if err := http.ListenAndServe(":8080", mux); err != nil {
log.Fatalf("start http server failed, error: %s\n", err.Error())
}
}