内容简介:本文首先介绍使用http标准库搭建web服务,共三种方式,然后简析内部实现原理,最后对http的使用做出总结。阅读本文需要简单的go基础知识和web开发相关知识。
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")
}
复制代码
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")
}
复制代码
mux := http.NewServeMux()
	mux.Handle("/hello", &helloHandler{})
	mux.Handle("/hi", &hiHandler{})
	
	server2 := http.Server{
    	Addr: "127.0.0.1:8082",
    	Handler:mux,
	}
复制代码
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")
}
复制代码
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标准库简析》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

猜你喜欢:

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