Go MUX 控制器返回 404

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

Go MUX controller returns 404

问题

我必须漏掉了一些非常明显的东西,但是我创建了一个MUX路由控制器,服务器返回404错误。运行以下代码:

package main

import (
	"fmt"
	"log"
	"net/http"
	"github.com/gorilla/mux"
)

func main() {
	router := mux.NewRouter()
	router.HandleFunc("/hi", SayHi)
	log.Fatal(http.ListenAndServe(":8080", router))
}

func SayHi(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Hi")
}

访问:http://localhost:8080/hi,我得到了一个404错误。

我做错了什么?

英文:

I must be missing something really obvious, but I've created a MUX routed controller and the server returns 404. Running the following:

package main

import (
	"fmt"
	"log"
	"net/http"
	"github.com/gorilla/mux"
)

func main() {
	router := mux.NewRouter()
	router.HandleFunc("/hi", SayHi)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func SayHi(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Hi")
}

Visit : http://localhost:8080/hi and I get a 404.

What am I doing wrong?

答案1

得分: 2

只需将router变量作为第二个参数传递给http.ListenAndServe(),而不是nil

英文:

Just pass router variable as second parameter to http.ListenAndServe() instead of nil

huangapple
  • 本文由 发表于 2017年5月22日 07:02:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/44102625.html
匿名

发表评论

匿名网友

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

确定