处理动态子域

时间:2018-06-20 16:14:52

标签: go mux

假设我的网站是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的初学者,所以我可能缺少一些概念

谢谢

1 个答案:

答案 0 :(得分:3)

您处在正确的轨道上。为每种域创建一个http.ServeMux,然后从Mux.ServeHTTP中的if / else语句调用这些mux。另外,将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
}