[英]Setting up a http handler in go
I was following the go tour and one of the exercises asked me to build a couple http handlers. 我正在进行巡回演出,其中一个练习要求我建立几个HTTP处理程序。 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. 代码可以编译并正常运行,但是我不确定为什么当我导航到
localhost:4000/string
或localhost:4000/struct
我得到的只是默认http处理程序中的404错误。
Am I missing a step here or? 我在这里错过了一步吗?
Your code stops at ListenAndServe
, which is blocking. 您的代码在被阻塞的
ListenAndServe
停止。 (BTW, if ListenAndServe
didn't block, main
would return and the process would exit) (顺便说一句,如果
ListenAndServe
没有阻止,则main
将返回并且该过程将退出)
Register the handlers before that. 在此之前注册处理程序。
Change main
from 从更改
main
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. http.ListenAndServe
阻止,直到您终止程序。
is common to add a log of the exit value: 添加退出值的日志很常见:
log.Fatal(http.ListenAndServe(...))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.