美文网首页
go实现http服务三

go实现http服务三

作者: Uzero | 来源:发表于2018-01-01 12:58 被阅读0次

    通过map来保存你注册的 handler , 底层通过ServeHTTP来进行转发。

    每个handler只有一个方法ServeHTTP,所以可以在ServeHTTP中进行路由的转发

    server3.go

    package main

    import (

            "io"

            "net/http"

            "log"

            "time"

    )

    var muxmap[string] func(http.ResponseWriter, *http.Request)

    func main () {

            server := &http.Server{

                  Addr:":6077",

                  Handler:&NewHandler{},

                  ReadTimeout:5 * time.Second,

           }

            // 路由注册

            mux = make(map[string]func(http.ResponseWriter, *http.Request))

            mux["/hello"] = sayThree

            mux["/say"]   = sayFive

            err := server.ListenAndServe()

            if err != nil {

                    log.Fatal(err)

            }

    }

    type NewHandlerstruct {}

    func (*NewHandler)ServeHTTP(w http.ResponseWriter, r *http.Request) {

            if fun, ok := mux[r.URL.String()]; ok {

                    fun(w, r)

                    return

            }    

            io.WriteString(w, "URL:" + r.URL.String())

    }

    func sayThree (w http.ResponseWriter, r *http.Request) {

            io.WriteString(w, "this is version 3")

    }

    func sayFive (w http.ResponseWriter, r *http.Request) {

            io.WriteString(w, "this is version 4")

    }

    go run server3.go

    相关文章

      网友评论

          本文标题:go实现http服务三

          本文链接:https://www.haomeiwen.com/subject/kpqtnxtx.html