gpt4 book ai didi

go - 处理动态子域

转载 作者:IT王子 更新时间:2023-10-29 01:56:59 26 4
gpt4 key购买 nike

假设我的网站是 http://soccer.com,我想支持无限数量的子域,例如:

  • http://cronaldo.soccer.com
  • http://messi.soccer.com
  • http://neymar.soccer.com
  • http://muller.soccer.com
  • ...

我还想保留一些子域,例如:

  • http://admin.soccer.com
  • http://help.soccer.com
  • ...

虽然玩家的子域将由相同的逻辑处理,但保留的子域不会。所以我需要 2 条路由或 2 个路由器?

这是我所拥有的:

package main

import (
"fmt"
"net/http"
"log"
"html/template"
"strings"
)

type Mux struct {
http.Handler
}

func (mux Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
domainParts := strings.Split(r.Host, ".")
fmt.Println("Here: " + domainParts[0])
if domainParts[0] == "admin" {
// assign route?
mux.ServeHTTP(w, r)
} else if domainParts[0] == "help" {
// assign route?
mux.ServeHTTP(w, r)
} else if isSubDomainValid(domainParts[0]) {
// assign route for player page?
mux.ServeHTTP(w, r)
} else {
// Handle 404
http.Error(w, "Not found", 404)
}
}

func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", HomeHandler)

http.ListenAndServe(":8080", mux)
}

func HomeHandler(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("index.html")
if err != nil {
log.Print("template parsing error: ", err)
}

err = t.Execute(w, nil)
if err != nil {
log.Print("template executing error: ", err)
}

但我不认为我这样做是对的。

fmt.Println("Here: "+ domainParts[0]) 从未出现,让我相信 ServeHTTP() 从未被调用。

我只是 Go 的初学者,所以我可能会遗漏一些概念

谢谢

最佳答案

您走在正确的轨道上。为每种域创建一个 http.ServeMux,并从 Mux.ServeHTTP 中的 if/else 语句调用这些多路复用器。此外,使用 Mux 作为根处理程序。

type Mux struct {
help, admin, sub, main *http.ServeMux
}

func (mux *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if isMainDomain(r.Host) {
mux.main.ServeHTTP(w, r)
return
}
domainParts := strings.Split(r.Host, ".")
if domainParts[0] == "admin" {
mux.admin.ServeHTTP(w, r)
} else if domainParts[0] == "help" {
mux.help.ServeHTTP(w, r)
} else if isSubDomainValid(domainParts[0]) {
mux.sub.ServeHTTP(w, r)
} else {
http.Error(w, "Not found", 404)
}
}

func main() {
mux := &Mux{
help: http.NewServeMux(),
admin: http.NewServeMux(),
sub: http.NewServeMux(),
main: http.NewServeMux(),
}

mux.help.HandleFunc("/", helpHomeHandler)
mux.admin.HandleFunc("/", adminHomeHandler)
mux.sub.HandleFunc("/", defaultSubdomainHomeHandler)
mux.main.HandleFunc("/", mainHomeHandler)

http.ListenAndServe(":8080", mux) // <-- use Mux value as root handler
}

关于go - 处理动态子域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50952793/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com