本章通过编写功能逐渐复杂的 web 服务器来让开发者对如何运用 go 语言有一个初步的了解。web 服务的地址 http://localhost:8000。
1. 启动一个最简单的 web 服务器
package mainimport ("fmt""log""net/http"
)func main() {http.HandleFunc("/", handler) //用handler函数处理根路由下的每个请求log.Fatal(http.ListenAndServe("localhost:8000", nil))
}// 将访问的路径返回到页面
func handler(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
}
2. 增加一些不同url进行不同处理的功能
package mainimport ("fmt""log""net/http""sync"
)var mu sync.Mutex
var count intfunc main() {http.HandleFunc("/", handler) // 用handler函数处理根路由 / 下的每个请求http.HandleFunc("/count", counter) // 用handler函数处理路径为 /count 的请求log.Fatal(http.ListenAndServe("localhost:8000", nil))
}// 将访问的路径返回到页面,并计数+1
func handler(w http.ResponseWriter, r *http.Request) {mu.Lock()count++mu.Unlock()fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
}// 返回计数值
func counter(w http.ResponseWriter, r *http.Request) {mu.Lock()fmt.Fprintf(w, "Count %d\n", count)mu.Unlock()
}