1.通过代理转换
后端服务
package main import ( "encoding/base64" "log" "net/http" "os" "os/signal" "strings" ) type webHandler struct { } func (webHandler) ServeHTTP (w http.ResponseWriter, r *http.Request ){ auth:= r.Header.Get("Authorization") log.Println(r.Header.Get("names")) if auth == "" { w.Header().Set("WWW-Authenticate",`Basic realm=11111"`) w.WriteHeader(http.StatusUnauthorized) return } log.Println(auth) authList := strings.Split(auth," ") log.Println(authList) if len(authList) ==2 && authList[0] =="Basic" { res,err:= base64.StdEncoding.DecodeString(authList[1]) if err != nil { log.Println("is errors") } if( (err ==nil) && (string(res) == "zhangsan:111111")){ w.Write([]byte("come in")) return } } w.Write([]byte("用户名密码错误")) } func main(){ c:=make(chan os.Signal)//信号 go func() { http.ListenAndServe(":9091",webHandler{}) }() signal.Notify(c,os.Interrupt) s:=<-c log.Println(s) }
2.前端
package main import ( "io/ioutil" "log" "net/http" ) type ProxyHandle struct { } func (p ProxyHandle) ServeHTTP(w http.ResponseWriter,r *http.Request){ defer func(){ if err:= recover();err != nil { w.WriteHeader(500) log.Println(err) } }() if r.URL.Path == "/a" { newrequest,_:=http.NewRequest(r.Method,"http://localhost:9091",r.Body)//生成一个新的请求 for k1,v1:=range r.Header { newrequest.Header.Add(k1,v1[0]) } req,_:=http.DefaultClient.Do(newrequest) for k,v:=range req.Header { w.Header().Set(k,v[0]) } w.WriteHeader(req.StatusCode) defer req.Body.Close() ss,_:=ioutil.ReadAll(req.Body) w.Write(ss) return } w.Write([]byte("<h1>defualt index</h1>")) } func main(){ http.ListenAndServe(":8080",&ProxyHandle{}) }
标签:http,log,err,req,代理,Header,func,basic,go From: https://www.cnblogs.com/zh718594493/p/16896611.html