快速创建一个httpserver
package main import ( "net/http" "fmt" ) type MyHandler struct{ } func(*MyHandler) ServeHTTP(write http.ResponseWriter,request *http.Request){ write.Write([]byte("hello,myhandler")); } func main(){ handler := new(MyHandler) server := http.Server{Addr:":8099",Handler:handler} err := server.ListenAndServe() if err != nil{ fmt.Println(err) } }
路由 设置cookie 注销 判断登录
package main import ( "net/http" "time" ) type MyHandler struct { } func(*MyHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request){ writer.Write([]byte("hello,myhandler")) } func main() { mymux:=http.NewServeMux() mymux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { writer.Write([]byte("index")) }) mymux.HandleFunc("/login", func(writer http.ResponseWriter, request *http.Request) { getUserName:= request.URL.Query().Get("username") if getUserName!=""{ c:=&http.Cookie{Name:"username",Value:getUserName,Path:"/"} http.SetCookie(writer,c) } writer.Write([]byte("这里是登录页面")); }) mymux.HandleFunc("/unlogin", func(writer http.ResponseWriter, request *http.Request) { c:=&http.Cookie{Name:"username",Value:"",Path:"/",Expires:time.Now().AddDate(-1,0,0)} http.SetCookie(writer,c) writer.Header().Set("Content-type","text/html") writer.Write([]byte("unlogin....")); script:=`<script> setTimeout(()=>{self.location='/'},2000) </script>` writer.Write([]byte(script)) }) http.ListenAndServe(":8099",mymux) }
自定义路由支持get、post
package main import ( "net/http" "gospace/core" ) type MyHandler struct { } func(*MyHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request){ writer.Write([]byte("hello,myhandler")) } func main() { router:=core.DefaultRouter() router.Get("/", func(writer http.ResponseWriter, request *http.Request) { writer.Write([]byte("get abc")) }) router.Post("/", func(writer http.ResponseWriter, request *http.Request) { writer.Write([]byte("post abc")) }) http.ListenAndServe(":8099",router) }
package core import ( "net/http" ) type MyRouter struct { Mapping map[string]map[string]http.HandlerFunc } func DefaultRouter() *MyRouter { return &MyRouter{make(map[string]map[string]http.HandlerFunc)} } func(this *MyRouter) Get(path string,f http.HandlerFunc) { if this.Mapping["GET"]==nil{ this.Mapping["GET"]=make(map[string]http.HandlerFunc) } this.Mapping["GET"][path]=f } func(this *MyRouter) Post(path string,f http.HandlerFunc) { if this.Mapping["POST"]==nil{ this.Mapping["POST"]=make(map[string]http.HandlerFunc) } this.Mapping["POST"][path]=f } func(this *MyRouter) ServeHTTP(writer http.ResponseWriter, request *http.Request){ f:=this.Mapping[request.Method][request.URL.Path] f(writer,request) }