大猩猩mux路由处理程序

huangapple go评论81阅读模式
英文:

gorilla mux router handlers

问题

我无法让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){
	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)
	}
}
英文:

I can not get the gorilla mux to work..

When requesting http://www.localhost:9000 this is returned by the web server 404 page not found

But this works http://localhost:9000/ and prints 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)
	}
}

答案1

得分: 2

你想要支持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)

	subrouter := r.Host("www.localhost").Subrouter()
	subrouter.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

英文:

You want to be able to support both localhost and 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)
        }
}

If you read the documentation carefully, you'll notice that r.Host() is just another pattern matching function. It doesn't set any global rule for that router.

if you want to make that rule to be inherited you'll need to use a subrouter:

subrouter := r.Host("www.localhost").Subrouter()

then you use "subrouter" in place of "r"

huangapple
  • 本文由 发表于 2014年9月29日 00:14:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/26086884.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定