第一种方法
后端代码:
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) }
标签:http,func,Request,golang,proxy,io,main,ResponseWriter From: https://www.cnblogs.com/zh718594493/p/16903116.html