Go Web
简介
来源于B站视频,
课程视频
Go Web
Web是基于http协议的一个服务,Go语言里面提供了一个完善的net/http包,通过http包可以很方便的就搭建起来一个可以运行的Web服务。
01 - 案例
HandleFunc
文档简介
能够注册监听的路径pattern
并设置访问当前路径触发的回调方法.
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
HandleFunc registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.
ListenAndServe
文档简介
设置监听对应的主机和端口以及对应的处理方法.
func ListenAndServe(addr string, handler Handler) error
ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives.
The handler is typically nil, in which case the DefaultServeMux is used.
ListenAndServe always returns a non-nil error.
案例能够监听localhost:8888并在页面中打印 Hello, World!
package main
import "net/http"
func main() {
http.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte("Hello, World!"))
})
http.ListenAndServe("localhost:8888", nil) // DefaultServeMux
}