参考Go web编程,很简单的程序:
大致的步骤:
- 绑定ip和端口
- 绑定对应的处理器或者处理器函数,有下面两种选择,选择一种即可监听ip及端口
- 处理器:
- 定义一个struct结构体
- 然后让这个结构体实现ServeHTTP的接口
- 创建一个该结构的实例
- 将该实例的地址(指针)作为参数传递给Handle
- 处理器函数
- 定义一个函数
- 该函数必须和ServeHTTP一样的函数签名
- 函数名直接作为参数传递给HandleFunc
- 处理器:
- 监听ip和port
- 使用浏览器访问绑定的ip加port,即可访问
使用处理器形式:
package main import ( "fmt" "net/http" ) type Home struct{} type About struct{} func (h *Home) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "this is home") } func (a *About) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "this is about") } func main() { server := http.Server{ Addr: "127.0.0.1:8080", } home := &Home{} about := &About{} http.Handle("/home", home) http.Handle("/about", about) server.ListenAndServe() }
使用处理器函数形式:
package main import ( "fmt" "net/http" ) func home(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "this is home2") } func about(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "this is about2") } func main() { server := http.Server{ Addr: "127.0.0.1:8080", } http.HandleFunc("/home", home) http.HandleFunc("/about", about) server.ListenAndServe() }