Google GO:路由请求处理神秘声明?

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

Google GO: routing request handling mystical declarations?

问题

我第一次使用Google GO玩耍。我已经扩展了“hello world”应用程序,尝试在init部分中定义路径。到目前为止,我已经做了以下工作:

package hello

import (
    "fmt"
    "net/http"
)

func init() {
    http.HandleFunc("/service", serviceHandler)
    http.HandleFunc("/site", siteHandler)
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello, there")
}

func serviceHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "this is Services")
}

func siteHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "this is Sites")
}

只有handler()回调函数被执行,其他函数被忽略。例如:http://myserver/service/foo打印出Hello, there。我希望它应该是this is Services

有没有更好的方法来进行服务路由?理想情况下,我希望它们是单独的脚本,但看起来Go只有一个脚本,因为app.yaml在脚本声明中需要一个特殊的字符串_go_app

谢谢!

英文:

I'm dorking around with Google GO for the first time. I've extended the "hello world" application to try to have paths defined in the init section. Here's what I've done so far:

package hello

import (
    "fmt"
    "net/http"
)

func init() {
	http.HandleFunc("/service", serviceHandler)
	http.HandleFunc("/site", siteHandler)
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello, there")
}

func serviceHandler( w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "this is Services")
}

func siteHandler( w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "this is Sites")
}

Only the handler() callback is ever executed -- the others are ignored. E.g.: http://myserver/service/foo prints Hello, there. I had hoped that it would be this is Services.

Is there a better way to do service routing? Ideally, I would expect these to be separate scripts anyway, but it looks like Go has only one script, based on the fact that the app.yaml requires a special string _go_app in the script declaration.

Thanks!

答案1

得分: 6

根据http://golang.org/pkg/net/http/#ServeMux上的文档,没有尾部斜杠的路径规范只能精确匹配该路径。在末尾添加斜杠,像这样:http.HandleFunc("/service/", serviceHandler),它将按照您的期望工作。

英文:

According to the documentation at: http://golang.org/pkg/net/http/#ServeMux

path specs that do not have a trailing slash only match that path exactly. Add a slash to the end like so: http.HandleFunc("/service/", serviceHandler) and it will work as you expect.

huangapple
  • 本文由 发表于 2012年9月7日 02:31:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/12306275.html
匿名

发表评论

匿名网友

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

确定