go - 从 postman 检查时获取 404 页面未找到错误

标签 go routing google-cloud-platform

我正在使用 goapp serve 运行以下代码。从 postman 检查时,以某种方式出现 404 找不到页面 错误。你能帮我解决这个问题吗

    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))

    }

在 postman 传递端点 http://localhost:8080/hello/hyderabad

最佳答案

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

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

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

   func init() {
        router := httprouter.New()
        router.GET("/", Index)
        router.GET("/hello/:name", Hello)
        http.Handle("/", router)
    }

关于go - 从 postman 检查时获取 404 页面未找到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47976333/

相关文章:

go - 尽管在启动应用程序时是私有(private)的,但如何从主包调用 main() 函数?

database - Go 中多线程 LevelDB 的合适方法是什么?

java - App Engine - LocalDatastoreService 加载 - 无法从后备存储加载

firebase - App Engine 和 Firebase 托管在一个域中

Node.js/快速路由

google-cloud-platform - GCP Notebook AI——具有写入权限的 SSH?

go - 将一个结构分配给 "structural identical"类型的另一结构

go - 具有动态类型的结构

Angular2 如何导航到用 id 属性标识的页面的特定部分

symfony - 填写所有必填参数