从邮递员检查时发现404页面未找到错误

问题描述 投票:0回答:1

我正在使用goapp serve运行以下代码。以某种方式从邮递员检查时得到404 page not found错误。你能帮我解决这个问题

    package hello

        import (
        "fmt"
        "net/http"

        "github.com/julienschmidt/httprouter"
    )

    func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
        fmt.Fprint(w, "Welcome!\n")
    }

    func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
        fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
    }

    func init() {
        router := httprouter.New()
        router.GET("/", Index)
        router.GET("/hello/:name", Hello)
//log.Fatal(http.ListenAndServe(":8080", router))

    }

在邮递员通过终点http://localhost:8080/hello/hyderabad

go routing google-cloud-platform gcp
1个回答
1
投票

扩展我上面的评论:处理函数(或来自julienschmidt/httprouter的路由器)不会注册自己。相反,它需要在http服务器上注册。

最简单的方法是使用以下命令注册默认的ServeMux:http.Handle("/", router)

因此,将init函数更改为以下内容将起作用:

   func init() {
        router := httprouter.New()
        router.GET("/", Index)
        router.GET("/hello/:name", Hello)
        http.Handle("/", router)
    }
© www.soinside.com 2019 - 2024. All rights reserved.