小编最近再看无闻的goweb视屏,总结视屏中三种go响应http的方法
1.直接用 http.HandleFunc() 函数
// object project main.gopackage mainimport ( ???"io" ???"log" ???"net/http")func main() { ???http.HandleFunc("/", sayhello) ???// 第一个参数代表访问的路径,第二个代表要执行的函数的名字 ???????err := http.ListenAndServe(":8080", nil) ???//设置端口号,第二个暂时没有,写为nil,在接下来的方法中介绍 ???if err != nil { ???????log.Fatal(err) ???????//如果err不为空,打印err ???}}//ResponseWriter为接口,Request为结构体func sayhello(w http.ResponseWriter, r *http.Request) { ???io.WriteString(w, "hello!this is version 1")}
2.介绍Handle方法
package main // dealFile project main.goimport ( ???"io" ???"log" ???"net/http" ???"os")func main() { ???//首先实现 NewServeMux()方法 ???max := http.NewServeMux() ???max.Handle("/", &myHandler{}) ???max.HandleFunc("/hello", sayhello) ???//静态文件的实现 ???wd, err := os.Getwd() ???if err != nil { ???????log.Fatal(err) ???} ???max.Handle("/static/", ???????http.StripPrefix("/static/", ???????????http.FileServer(http.Dir(wd)))) ???//设置监听的端口号 ???err = http.ListenAndServe(":8080", max) ???if err != nil { ???????log.Fatal(err) ???}}type myHandler struct{}//实现ServeHTTP方法func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ???io.WriteString(w, "URL:"+r.URL.String())}func sayhello(w http.ResponseWriter, r *http.Request) { ???io.WriteString(w, "Hello world,this is version 2")}
3.Server
package mainimport ( ???"io" ???"log" ???"net/http" ???"time")var mux map[string]func(http.ResponseWriter, *http.Request)func main() { ???server := http.Server{ ???????Addr: ???????":8080", //端口号 ???????Handler: ????&myHandler{}, ?//实现的Handler ???????ReadTimeout: 5 * time.Second, ?//响应等待时间 ???} ???mux = make(map[string]func(http.ResponseWriter, *http.Request)) ???mux["/hello"] = sayHello ???mux["/bye"] = sayBye ???err := server.ListenAndServe() ???if err != nil { ???????log.Fatal(err) ???}}type myHandler struct{}func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ???//判断URL是否为空并输出 ???if h, ok := mux[r.URL.String()]; ok { ???????h(w, r) ???????return ???} ???io.WriteString(w, "URL:"+r.URL.String())}func sayHello(w http.ResponseWriter, r *http.Request) { ???io.WriteString(w, "Hello World")}func sayBye(w http.ResponseWriter, r *http.Request) { ???io.WriteString(w, "Bye Bye")}
响应http的三种方法
原文地址:https://www.cnblogs.com/limozi/p/8145139.html