内容简介:本文首先介绍使用http标准库搭建web服务,共三种方式,然后简析内部实现原理,最后对http的使用做出总结。阅读本文需要简单的go基础知识和web开发相关知识。
本文首先介绍使用http标准库搭建web服务,共三种方式,然后简析内部实现原理,最后对http的使用做出总结。阅读本文需要简单的 go 基础知识和web开发相关知识。
1.使用http搭建简单的web服务
1.1单个handler形式,示例如下:
func main() {
server := http.Server{
Addr: "127.0.0.1:8081",
Handler: &helloHandler{},
}
_ = server.ListenAndServe()
}
type helloHandler struct{}
func (h *helloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "hello World")
}
复制代码
-
监听
8081端口。 -
只有一个
Handler的实现,所有的请求都由helloHandler的ServeHTTP方法处理。访问localhost:8081、localhost:8081/a、localhost:8081/a/a都返回hello World。 - 显然此方式很简陋无法满足需求。
1.2多个handler,示例如下:
func main() {
server2 := http.Server{
Addr: "127.0.0.1:8082",
}
http.Handle("/hello", &helloHandler{})
http.Handle("/hi", &hiHandler{})
_ = server2.ListenAndServe()
}
type helloHandler struct{}
func (h *helloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "hello World")
}
type hiHandler struct{}
func (h *hiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "hi World")
}
复制代码
-
监听
8082端口。 -
注册了
/hello、/hi两个路由,helloHandler、hiHandler的ServeHTTP方法分别处理。 -
方式一相比较,没有为
Server指定Handler属性。而http库为我们默认指定了一个名称为DefaultServeMux(server.go:2196)的Handler。 可以自己指定Handler,如下。
mux := http.NewServeMux()
mux.Handle("/hello", &helloHandler{})
mux.Handle("/hi", &hiHandler{})
server2 := http.Server{
Addr: "127.0.0.1:8082",
Handler:mux,
}
复制代码
1.3HandlerFunc,示例如下:
func main() {
server3 := http.Server{
Addr: "127.0.0.1:8083",
}
http.HandleFunc("/hello", helloFunc)
http.HandleFunc("/hi", hiFunc)
_ = server3.ListenAndServe()
}
func helloFunc(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "hello World")
}
func hiFunc(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "hi World")
}
复制代码
-
监听
8083端口。 -
注册了
/hello、/hi两个路由,分别由helloFunc、hiFunc两个函数处理。 -
同方式二一样,并没有为
Server指定Handler属性,由标准库自己指定。可以自己指定Handler,如下。
mux := http.NewServeMux()
mux.HandleFunc("/hello",helloFunc)
mux.HandleFunc("/hi",hiFunc)
server3 := http.Server{
Addr: "127.0.0.1:8083",
Handler:mux,
}
复制代码
以上所述就是小编给大家介绍的《Golang web之http标准库简析》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Computational Advertising
by Kushal Dave、Vasudeva Varma / Now Publishers Inc / 2014
Computational Advertising (CA), popularly known as online advertising or Web advertising, refers to finding the most relevant ads matching a particular context on the Web. The context depends on the t......一起来看看 《Computational Advertising》 这本书的介绍吧!