golang 实现反向代理

简介

有时候,需要针对http 做反向代理,用来做一些事情。

如: 修改包头、重定向、过滤、防御、路由等等

golang 实现

使用golang 包,十分简单地实现一个高性能的反向代理

依赖包

	"net/http"
	"net/http/httputil"
	"net/url"

源码

package main

import (
	"net/http"
	"net/http/httputil"
	"net/url"
)

func main() {
	backendService := "localhost:8081"
	rpURL, err := url.Parse(backendService)
	if err != nil {
		panic(err)
	}
	proxy := httputil.NewSingleHostReverseProxy(rpURL)
	director := proxy.Director
	proxy.Director = func(r *http.Request) {
		director(r)
		r.Host = "target.local"
	}
	http.ListenAndServe(":8080", proxy)
}

进阶

可以通过自定义Director ,来代理不通的后端,具体可看NewSingleHostReverseProxy 函数是怎么实现的

// NewSingleHostReverseProxy returns a new ReverseProxy that routes
// URLs to the scheme, host, and base path provided in target. If the
// target's path is "/base" and the incoming request was for "/dir",
// the target request will be for /base/dir.
// NewSingleHostReverseProxy does not rewrite the Host header.
// To rewrite Host headers, use ReverseProxy directly with a custom
// Director policy.
func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {
	targetQuery := target.RawQuery
	director := func(req *http.Request) {
		req.URL.Scheme = target.Scheme
		req.URL.Host = target.Host
		req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
		if targetQuery == "" || req.URL.RawQuery == "" {
			req.URL.RawQuery = targetQuery + req.URL.RawQuery
		} else {
			req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
		}
		if _, ok := req.Header["User-Agent"]; !ok {
			// explicitly disable User-Agent so it's not set to default value
			req.Header.Set("User-Agent", "")
		}
	}
	return &ReverseProxy{Director: director}
}
humboldt Written by:

humboldt 的趣味程序园