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

在自己的网站部署TLS 1.3

前不久Go 1.12 发布,对TLS 1.3 作初步支持,对使用Go 开发的后台来说,这是一个很好的消息。但要启用TLS 1.3 必须添加一个编译参数 `GODEBUG=tls13=1`,等Go 1.13 就默认支持。...

Golang http client 处理重定向网页

假设一个网址有多个重定向,A-B-C-D,使用 http.Client.Get 最后取得的内容是网址D的内容,我们该手动处理包含重定向的网址。...

Golang Web 程序生产环境独立部署示例

一个 web 应用通常是跑在一个前端代理,如 Nginx 后,这样可以方便的在同一个服务器部署多个应用。这里说的独立部署是指让 go web 程序直接暴露在外面,独占 443、80 端口(俗称裸跑)。这样做除了性能有些提高外,更重要的是部署方便。...

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

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