GolangNote

Golang笔记

Golang 单实例实现网站多域名请求

Permalink

有时候写网站,为了统一的后端,把不同业务都集中到一个后端,这时就需要处理多域名的请求,在 Go http server 里实现很简单,只需把不同域名映射到不同的 http.Handler

下面是一个简单的例子:

定义一个 http.Handler map HostSwitch,并定义一个方法 ServeHTTP(w http.ResponseWriter, r *http.Request)

Go: HostSwitch
1
2
3
4
5
6
7
8
9
10
type HostSwitch map[string]http.Handler

// Implement the ServerHTTP method
func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if handler, ok := hs[r.Host]; ok && handler != nil {
        handler.ServeHTTP(w, r)
    } else {
        http.Error(w, "Forbidden", http.StatusForbidden)
    }
}

在main 函数里使用:

Go: main func
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(w, "Welcome to the first home page!")
    })

    muxTwo := http.NewServeMux()
    muxTwo.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(w, "Welcome to the second home page!")
    })

    hs := make(HostSwitch)
    hs["example-one.local:8080"] = mux
    hs["example-two.local:8080"] = muxTwo

    log.Fatal(http.ListenAndServe(":8080", hs))
}

总结

这里只是一个简单的使用 go 原生库实现的多域名映射。现在许多 web 框架都支持多域名、多字域名或泛域名请求。

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

Related articles

Write a Comment to "Golang 单实例实现网站多域名请求"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms