Golang 实现多域名反向代理

Golang 实现多域名反向代理,可以把不同的域名指向不同的应用。

package main

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

var (
	// 建立域名和目标map
	hostTarget = map[string]string{
		"app1.domain.com": "http://192.168.1.2/owncloud",
		"app2.domain.com": "http://192.168.1.2:8080",
		"app3.domain.com": "http://192.168.1.2:8888",
	}
	// 用于缓存 httputil.ReverseProxy
	hostProxy map[string]*httputil.ReverseProxy
)

type baseHandle struct{}

func (h *baseHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	host := r.Host

	// 直接从缓存取出
	if fn, ok := hostProxy[host]; ok {
		fn.ServeHTTP(w, r)
		return
	}

	// 检查域名白名单
	if target, ok := hostTarget[host]; ok {
		remoteUrl, err := url.Parse(target)
		if err != nil {
			log.Println("target parse fail:", err)
			return
		}

		proxy := httputil.NewSingleHostReverseProxy(remoteUrl)
		hostProxy[host] = proxy // 放入缓存
		proxy.ServeHTTP(w, r)
		return
	}
	w.Write([]byte("403: Host forbidden " + host))
}

func main() {

	h := &baseHandle{}
	http.Handle("/", h)

	server := &http.Server{
		Addr:    ":8082",
		Handler: h,
	}
	log.Fatal(server.ListenAndServe())
}
Relative Articles
评论