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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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())
}

本文网址: https://golangnote.com/topic/212.html 转摘请注明来源