share/share.go
/****** ** @创建时间 : 2020/5/25 20:26 ** @作者 : SongZhiBin ******/ package share import ( "fmt" "net/http" "net/http/httputil" "net/url" "os" ) // ========= global variable var Config conf var LogOut *os.File // ========== Struct type conf struct { TargetIP string TargetPort int LocalPort int } // 转发中间件 func (c *conf) Forward(w http.ResponseWriter, r *http.Request) { u, _ := url.Parse(fmt.Sprintf("http://%s:%d/", Config.TargetIP, Config.TargetPort)) proxy := httputil.NewSingleHostReverseProxy(u) proxy.ServeHTTP(w, r) }
config.txt
[target] TargetIP = 127.0.0.1 TargetPort = 8080 LocalPort = 80
run.go
/****** ** @创建时间 : 2020/5/25 19:09 ** @作者 : SongZhiBin ******/ package main import ( "fmt" "gopkg.in/ini.v1" "net/http" "os" ) import "Songzhibin/HttpAgent/share" func main() { // 读取配置文件 share.LogOut = os.Stdout cfg, err := ini.Load("./config.txt") if err != nil { // 读取失败,使用默认配置 share.Config.TargetIP = "127.0.0.1" share.Config.TargetPort = 80 share.Config.LocalPort = 80 fmt.Fprintf(share.LogOut, "使用默认配置->TargetIP:%s TargetPort:%d ", share.Config.TargetIP, share.Config.TargetPort) } err = cfg.Section("target").MapTo(&share.Config) if err != nil { fmt.Fprintf(share.LogOut, "MapTo映射失败->Err:%s ", err) return } fmt.Fprintf(share.LogOut, "配置文件启动->TargetIP:%s TargetPort:%d ", share.Config.TargetIP, share.Config.TargetPort) http.HandleFunc("/", share.Config.Forward) // 设置默认路由 err = http.ListenAndServe(fmt.Sprintf(":%d", share.Config.LocalPort), nil) if err != nil { fmt.Printf("http server failed, err:%v ", err) return } }