Golang web之http标准库简析

栏目: Go · 发布时间: 4年前

内容简介:本文首先介绍使用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 的实现,所有的请求都由 helloHandlerServeHTTP 方法处理。访问 localhost:8081localhost:8081/alocalhost: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 两个路由, helloHandlerhiHandlerServeHTTP 方法分别处理。
  • 方式一相比较,没有为 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 两个路由,分别由 helloFunchiFunc 两个函数处理。
  • 同方式二一样,并没有为 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标准库简析》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Caching

Web Caching

Duane Wessels / O'Reilly Media, Inc. / 2001-6 / 39.95美元

On the World Wide Web, speed and efficiency are vital. Users have little patience for slow web pages, while network administrators want to make the most of their available bandwidth. A properly design......一起来看看 《Web Caching》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

html转js在线工具
html转js在线工具

html转js在线工具