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

Golang 数据库 Bolt 碎片整理

Bolt 是一个优秀、纯 Go 实现、支持 ACID 事务的嵌入式 Key/Value 数据库。但在使用过程中会有很多空间碎片。一般数据库占用的空间是元数据空间的 1.5~4 倍。Bolt 没有内置的压缩功能,需要手动压缩。...

Golang Range 的性能提升Tip

Go 语言里使用 range 可以方便遍历数组(array)、切片(slice)、字典(map)和信道(chan)。这里主要关注他们的性能。...

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

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 1ms