使用 gorilla mux 指向域去服务器

Point domain to go server with gorilla mux

我有一个小型服务器,我希望该服务器使用 gorilla/mux 程序包收听我的自定义域 sftablet.dev。

代码如下:

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()
    r.Host("sftablet.dev")
    r.HandleFunc("/", HomeHandler)
    r.HandleFunc("/products", ProductsHandler)
    http.ListenAndServe(":8080", r)
}

func HomeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hey, this is homepage")
}

func ProductsHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hey, this is products")
}

我还在主机文件中添加了这个:

127.0.0.1       sftablet.dev

但由于某种原因,它不起作用。如果我转到 127.0.0.1:8080,它确实有效,但当我访问 http://sftablet.dev/ 时却无效。还清除了 DNS 缓存。

http://sftablet.dev/ 默认查询端口 80

您的服务器只监听端口 8080。http://sftablet.dev:8080/ 应该可以。

不使用 r.Host("sftablet.dev"),而是将域名托管服务商移至 http.ListenAndServe 方法:

func main() {
    r := mux.NewRouter()
    // r.Host("sftablet.dev")
    r.HandleFunc("/", HomeHandler)
    r.HandleFunc("/products", ProductsHandler)
    http.ListenAndServe("sftablet.dev:8080", r)
}