4.golang http proxy反向代理
第一种方法
后端代码:
package main import ( "io" "net/http" ) func web1Func( w http.ResponseWriter, r* http.Request){ io.WriteString(w,"<h1>this is test info web1</h1>") } func web2Func(w http.ResponseWriter, r*http.Request){ io.WriteString(w,"<h1>this is test info web2</h1>") } func main(){ http.HandleFunc("/web1",web1Func) http.HandleFunc("/web2",web2Func) http.ListenAndServe(":9001",nil) }
前端代码:
package main import ( "io/ioutil" "log" "net/http" ) type MyMux struct { } func (MyMux) ServeHTTP(w http.ResponseWriter,r *http.Request){ if r.URL.Path == "/web1" { newRequest,_:= http.NewRequest(r.Method,"http://localhost:9001/web1",r.Body) req,err:=http.DefaultClient.Do(newRequest) if err != nil { log.Println("is error") return } data,_:= ioutil.ReadAll(req.Body) w.Write(data) return } if r.URL.Path == "/web2" { newRequest,_:= http.NewRequest(r.Method,"http://localhost:9001/web2",r.Body) req,err:=http.DefaultClient.Do(newRequest) if err != nil { log.Println("is error") return } data,_:= ioutil.ReadAll(req.Body) w.Write(data) return } } func main(){ http.Handle("/",MyMux{}) http.ListenAndServe(":7001",nil) }
思考:第一种方法虽然可行,但是header头里面的信息传递不到后面去,如果需要传递的话,还必须加工http的header头
第二种方法
后端代码:
package main import ( "io" "net/http" ) func web1Func( w http.ResponseWriter, r* http.Request){ io.WriteString(w,"<h1>this is test info web1</h1>") } func web2Func(w http.ResponseWriter, r*http.Request){ io.WriteString(w,"<h1>this is test info web2</h1>") } func web3Func(w http.ResponseWriter, r*http.Request){ io.WriteString(w,"<h1>this is test info web3</h1>") } func main(){ http.HandleFunc("/web1",web1Func) http.HandleFunc("/web2",web2Func) http.HandleFunc("/web3",web3Func) http.ListenAndServe(":9001",nil) }
前端代码
package main import ( "net/http" "net/http/httputil" "net/url" ) type MyMux struct { } //简单反向代理代码最少,heaer也传递过去了 func (MyMux) ServeHTTP(w http.ResponseWriter,r *http.Request){ sendurl:="http://localhost:9001" target,_:=url.Parse(sendurl) proxy:=httputil.NewSingleHostReverseProxy(target) proxy.ServeHTTP(w,r) } func main(){ http.Handle("/",MyMux{}) http.ListenAndServe(":7001",nil) }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
2020-11-18 go里面面向对象