gorilla mux路由器处理程序
我无法让gorilla mux工作 请求gorilla mux路由器处理程序,go,mux,Go,Mux,我无法让gorilla mux工作 请求http://www.localhost:9000这是由web服务器返回的404未找到页面 但这是有效的http://localhost:9000/并打印Hello world package main import ( "net/http" "fmt" "log" "github.com/gorilla/mux" ) func Handler(w http.ResponseWriter, r *http.Request
http://www.localhost:9000
这是由web服务器返回的404未找到页面
但这是有效的http://localhost:9000/
并打印Hello world
package main
import (
"net/http"
"fmt"
"log"
"github.com/gorilla/mux"
)
func Handler(w http.ResponseWriter, r *http.Request){
fmt.Fprint(w, "Hello world")
}
func main(){
r := mux.NewRouter()
r.Host("www.localhost")
r.HandleFunc("/", Handler)
err := http.ListenAndServe(":9000", r)
if err != nil {
log.Fatal("ListenAndServe error: ", err)
}
}
您希望能够同时支持localhost和www.localhost
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
func Handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello world")
}
func main() {
r := mux.NewRouter()
r.Host("www.localhost").Path("/").HandlerFunc(Handler)
r.HandleFunc("/", Handler)
err := http.ListenAndServe(":9000", r)
if err != nil {
log.Fatal("ListenAndServe error: ", err)
}
}
如果仔细阅读文档,您会注意到r.Host()只是另一个模式匹配函数。它没有为该路由器设置任何全局规则
如果要使该规则被继承,则需要使用子计算机:
subrouter := r.Host("www.localhost").Subrouter()
然后使用“subrouter”代替“r”/etc/hosts进行设置。。Web服务器在
www.localhost
上响应,但使用404