参考 Go web 编程, 很简单的程序:
大致的步骤:
绑定 ip 和端口
绑定对应的处理器或者处理器函数, 有下面两种选择, 选择一种即可监听 ip 及端口
处理器:
定义一个 struct 结构体
然后让这个结构体实现 ServeHTTP 的接口
创建一个该结构的实例
将该实例的地址 (指针) 作为参数传递给 Handle
处理器函数
定义一个函数
该函数必须和 ServeHTTP 一样的函数签名
函数名直接作为参数传递给 HandleFunc
访问绑定的 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()
- }
来源: http://www.bubuko.com/infodetail-2534832.html