http.Handler

下面是一个简单的例子:

http.HandlerHostSwitchServeHTTP(w http.ResponseWriter, r *http.Request)
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 函数里使用:

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 转摘请注明来源