golang http(s)请求转发

栏目: Go · 发布时间: 5年前

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")
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

BSD Hacks

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》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具