package main//gohttp底层实现,通过gohttp不是通过beego实现的输出//import ( "io" "log" "net/http")func main() { //设置路由 http.HandleFunc("/", sayHello) err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal(err) }}func sayHello(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hello vwesion1")}
package main//gohttp第二个版本:通过mux,handler实现路由import ( "io" "log" "net/http")func main() { mux := http.NewServeMux() //ServeMux//实现handler注册到ServeMux然后在进行路由的注册 mux.Handle("/", &myHandler{}) //注册路由和handler mux.Handle("/hello", sayHello) //通过函数注册路由 err := http.ListenAndServe(":8080", mux) if err != nil { log.Fatal(err) }}type myHandler struct { //这个handle要实现ServerHTTP方法}func (this *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hello vwesion2,"+r.URL.String())}func sayHello(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hello vwesion2,"+r.URL.String())}
package main//模拟gohttp底层,第三个版本import ( "fmt" "io" "log" "net/http" "os" //获取静态文件 "time")func main() { server := http.Server{ Addr: ":8080", Handler: &myHandler{}, //自定义handler ReadTimeout: 5 * time.Second, } myMux = make(map[string]func(http.ResponseWriter, *http.Request)) //初始化map myMux["/"] = sayHello //访问根目录调用sayHellp方法 myMux["/bye"] = sayBye //访问/bye调用sayBye方法 err := server.ListenAndServe() if err != nil { log.Fatal(err) }}type myHandler struct{}func (this *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { //handler来解析url,调用不同的方法, if h, ok := myMux[r.URL.String()]; ok { //if ok 对map的断言,ok是判断存不存在,h是获取的map的value, fmt.Println(h, ok) h(w, r) return } io.WriteString(w, "uuuu,"+r.URL.String())}var myMux map[string]func(http.ResponseWriter, *http.Request) //自定义mux,根据不同的string调用不同的方法func sayHello(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hello "+r.URL.String())}func sayBye(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "sayBye "+r.URL.String())}
package main//获取静态文件import ( "io" "log" "net/http" "os" //获取路径,静态文件服务器要获取绝对路径,根据当前路径定位到绝对路径,)func main() { mux := http.NewServeMux() //ServeMux//实现handler注册到ServeMux然后在进行路由的注册 mux.Handle("/", &myHandler{}) //注册路由和handler mux.Handle("/hello", sayHello) //通过函数注册路由 wd, err := os.Getwd() //wd是当前路径 if err != nil { log.Fatal(err) } mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(wd)))) //StripPrefix去除static前缀 err = http.ListenAndServe(":8080", mux) if err != nil { log.Fatal(err) }}type myHandler struct { //这个handle要实现ServerHTTP方法}func (this *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hello vwesion2,"+r.URL.String())}func sayHello(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hello vwesion2,"+r.URL.String())}