### 第一种 http.ListenAndServe 第二个参数就是处理函数,只需要继承 Handler interface(也就是有ServeHTTP函数) 以下代码处理函数是Myhandler.ServeHTTP,在里面可以进行自定义路由 ```go type Myhandler struct { } func (* Myhandler)ServeHTTP(write http.ResponseWriter,request *http.Request) { write.Write([]byte("爱的供养123123")) } func main(){ //开启服务并且坚挺 err:=http.ListenAndServe(":8099",&Myhandler) //等同于下面 //开启服务 server:=http.Server{Addr:":8099",Handler:&Myhandler} //启动监听浏览器连接 err:=server.ListenAndServe() if err!=nil{ fmt.Println(err) } } ``` ### 第二种 如果server对象不提供handler,则启用默认ServeMux,这是一个路由管理器 看源码http.HandleFunc 执行最终返回对象 ServeMux ```go func main() { //域名/根目录就能访问 http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { writer.Write([]byte("hello")) }) //****/abc http.HandleFunc("/abc", func(writer http.ResponseWriter, request *http.Request) { writer.Write([]byte("hello")) }) server:=http.Server{Addr:":8099"} } server.ListenAndServe() ``` ### 第三种 其实就是第二种,因为 http.HandleFunc 执行最终返回对象 ServeMux ,所以 ```go MyMux:=http.NewServeMux() MyMux.HandleFunc("/",func(writer http.ResponseWriter, request *http.Request){ writer.Write([]byte("默认页面")) }) //error 是自定义的一个错误判断 error:=tool.Error{} error.CatchError() err:=http.ListenAndServe(":8099",MyMux) error.CheckError(err) ``` ### 第四种-自定义 #### 说明 1. GO自定义路由类,假如需要区分GET POST 2. 那个类需要几个东西 3. 需要继承handler类 就是要包含ListenAndServe方法,不然没法自定义,它就是 http.ListenAndServe(":8090",MyRouter) 第二个参数,相当于接管了处理方法 4. 类里面需要储存请求方法 request.Method 5. 类里面需要储存请求url request.request.URL.Path 6. 类里面需要储存处理方法 HandlerFunc * 浏览器请求,根据请求方法,和请求路径,进入对应的处理方法 * 当然之前就要配置 请求方法+请求路径对应的处理方法;没有就要设置默认 Mapping map[string]map[string]http.HandlerFunc [请求方法][请求路径][处理方法] 一. main函数 ```go package main import ( "golang/appmain/socket/server/core" "net/http" func main() { MyRouter:=core.DefaultRouter() MyRouter.Get("/", func(writer http.ResponseWriter, request *http.Request) { writer.Write([]byte("get abc")) }) MyRouter.Post("/", func(writer http.ResponseWriter, request *http.Request) { writer.Write([]byte("post abc")) }) http.ListenAndServe(":8090",MyRouter) } ``` 二. core ```go 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){ //writer.Write([]byte("你好啊")) f:=this.Mapping[request.Method][request.URL.Path] f(writer,request) } ```