1 Star 0 Fork 0

永恒 / golang

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
main.go 2.77 KB
一键复制 编辑 原始数据 按行查看 历史
永恒 提交于 2022-07-31 16:32 . add httpserver dockerfile 20220731
package main
import (
"fmt"
"log"
"net"
"net/http"
"net/http/pprof"
"os"
"strings"
)
func index(w http.ResponseWriter, r *http.Request) {
//w.Write([]byte("<h1>welcome to cloudnative</h1>"))
//03 读取当前系统的环境变量中的VERSION 配置,并写入 response header
//手动构造version变量
os.Setenv("VERSION", "v1.0")
version := os.Getenv("VERSION")
w.Header().Set("VERSION", version)
fmt.Printf("os version: %s \n", version)
//02 接收客户端request,并将request中带的header 写入 response header
for k, v := range r.Header {
for _, vv := range v {
fmt.Printf("Header key: %s, Header value: %s \n", k, vv)
w.Header().Set(k, vv)
}
}
//04 记录日志并输出
//clientIP := getCurrentIP(r)
clientIP := ClientIP(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) {
//Fprintf: 来格式化并输出到 io.writers 而不是 os.Stdout
fmt.Fprintf(w, "working")
}
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 main() {
// NewServeMux可以创建一个ServeMux实例,ServeMux同时也实现了ServeHTTP方法,因此
//代码中的mux也是一种handler。把它当成参数传给http.ListenAndServe方法,后者会把
//mux传给Server实例。因为指定了handler,因此整个http服务就不再是DefaultServeMux,
//而是mux,无论是在注册路由还是提供请求服务的时候。
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("/healthz", healthz)
if err := http.ListenAndServe(":8080", mux); err != nil {
log.Fatalf("start http server failed, err: %s\n", err.Error())
}
}
1
https://gitee.com/eternal007/golang.git
git@gitee.com:eternal007/golang.git
eternal007
golang
golang
65373d97cc53

搜索帮助