英文:
Setting up a http handler in go
问题
我正在遵循Go Tour,并且其中一个练习要求我构建一对HTTP处理程序。
以下是代码:
package main
import (
    "fmt"
    "net/http"
)
type String string
type Struct struct {
  Greeting string
  Punct string
  Who string
}
func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request){
    fmt.Fprint(w, s)
}
func (s *Struct) ServeHTTP(w http.ResponseWriter, r *http.Request){
  fmt.Fprint(w, "This is a struct. Yey!")
}
func main() {
    // 在这里添加你的http.Handle调用
    http.ListenAndServe("localhost:4000", nil)
    http.Handle("/string", String("I'm a frayed knot"))
    http.Handle("/struct", &Struct{"Hello",":","Gophers!"})
}
代码可以编译和运行,但是当我访问localhost:4000/string或localhost:4000/struct时,我只得到了默认的HTTP处理程序返回的404错误。
我是否漏掉了什么步骤?
英文:
I was following the go tour and one of the exercises asked me to build a couple http handlers.
Here is the code:
    package main
import (
    "fmt"
    "net/http"
)
type String string
type Struct struct {
  Greeting string
  Punct string
  Who string
}
func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request){
    fmt.Fprint(w, s)
}
func (s *Struct) ServeHTTP(w http.ResponseWriter, r *http.Request){
  fmt.Fprint(w, "This is a struct. Yey!")
}
func main() {
    // your http.Handle calls here
    http.ListenAndServe("localhost:4000", nil)
    http.Handle("/string", String("I'm a frayed knot"))
    http.Handle("/struct", &Struct{"Hello",":","Gophers!"})
}
The code compiles & runs just fine however I am not sure why when I navigate to localhost:4000/string or localhost:4000/struct all I get is a 404 error from the default http handler.
Am I missing a step here or?
答案1
得分: 3
你的代码停在ListenAndServe这里,它是一个阻塞的操作。(顺便说一下,如果ListenAndServe不阻塞,main函数会返回并且进程会退出)
在此之前注册处理程序。
英文:
Your code stops at ListenAndServe, which is blocking. (BTW, if ListenAndServe didn't block, main would return and the process would exit)
Register the handlers before that.
答案2
得分: 1
将main函数中的代码进行修改,修改后的代码如下:
func main() {
    http.Handle("/string", String("I'm a frayed knot"))
    http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})
    // your http.Handle calls here
    log.Fatal(http.ListenAndServe("localhost:4000", nil))
}
http.ListenAndServe会阻塞程序直到终止。
通常会添加一个记录退出值的日志:
log.Fatal(http.ListenAndServe(...))
英文:
Change main from
func main() {
    // your http.Handle calls here
    http.ListenAndServe("localhost:4000", nil)
    http.Handle("/string", String("I'm a frayed knot"))
    http.Handle("/struct", &Struct{"Hello",":","Gophers!"})
}
to
func main() {
    http.Handle("/string", String("I'm a frayed knot"))
    http.Handle("/struct", &Struct{"Hello",":","Gophers!"})
    // your http.Handle calls here
    http.ListenAndServe("localhost:4000", nil)
}
http.ListenAndServe blocks until you terminate the program.
is common to add a log of the exit value:
log.Fatal(http.ListenAndServe(...))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论