func main(){ router := gin.Default()//创建一个router router.Use(MiddleWare())//中间件,起拦截器的作用 router.Any("/*action", Forward)//所有请求都会经过Forward函数转发 router.Run(":8000") } func Forward(c *gin.Context) { targetHost := &httputils.TargetHost{ Host: "www.baidu.com", IsHttps: false, } HostReverseProxy(c.Writer, c.Request, targetHost) } func HostReverseProxy(w http.ResponseWriter, req *http.Request, targetHost *TargetHost) { host := "" if targetHost.IsHttps { host = host + "https://" } else { host = host + "http://" } remote, err := url.Parse(host + targetHost.Host) if err != nil { log.Errorf("err:%s", err) w.WriteHeader(http.StatusInternalServerError) return } proxy := httputil.NewSingleHostReverseProxy(remote) if targetHost.IsHttps { tls, err := GetVerTLSConfig(targetHost.CAPath) if err != nil { log.Errorf("https crt error: %s", err) w.WriteHeader(http.StatusInternalServerError) return } var pTransport http.RoundTripper = &http.Transport{ Dial: func(netw, addr string) (net.Conn, error) { c, err := net.DialTimeout(netw, addr, time.Second*time.Duration(DialTimeout)) if err != nil { return nil, err } return c, nil }, ResponseHeaderTimeout: time.Second * time.Duration(ResponseHeaderTimeout), TLSClientConfig: tls, } proxy.Transport = pTransport } proxy.ServeHTTP(w, req) } type TargetHost struct { Host string IsHttps bool CAPath string } func MiddleWare() gin.HandlerFunc { return func(c *gin.Context) { account := c.Request.Header.Get("ename")//从请求头中获取ename字段 if account == "" { c.JSON(http.StatusOK, httputils.Response{ Code: 400002, Message: "用户未登录", }) c.Abort() return } fmt.Println("before middleware") c.Set("request", "clinet_request") c.Next() fmt.Println("before middleware") } }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- Redis(十二):redis请求转发的实现
- SpringCloud组件: GateWay整合Eureka转发服务请求
- HttpServletRequest 接口、HttpServletResponse 接口、请求转发与重定向
- node.js创建aria2代理服务器:使用net.socket转发rpc或http request请求,替换websocket
- iOS 消息转发
- SSH端口转发
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
BSD Hacks
Dru Lavigne / O'Reilly Media, Inc. / 2004-05-24 / USD 24.95
If you want more than your average BSD user--you want to explore and experiment, unearth shortcuts, create useful tools, and come up with fun things to try on your own--BSD Hacks is a must-have. This ......一起来看看 《BSD Hacks》 这本书的介绍吧!