手把手教媳婦-封裝簡易的http路由(二)

2020-07-24  本文已影响0人  牛空空

我媳妇觉得还是可以继续改进,那就继续改进下吧,将rest方法,简化下,然后http.ResponseWriter,http.Request对象封装下
context-封装

package main

import "net/http"

type Context struct {
    http.ResponseWriter
    *http.Request
}

type Handler func(*Context)

router修改下

package main

import (
    "log"
    "net/http"
)

type Router interface {
    GET(string, Handler)
    POST(string, Handler)
    DELETE(string, Handler)
    PUT(string, Handler)
}

type Kevin struct {
    handlers map[string]map[string]Handler
}

func NewKevin() *Kevin {

    return &Kevin{
        handlers: make(map[string]map[string]Handler),
    }

}

func (t *Kevin) GET(path string, h Handler) {

    if _, ok := t.handlers["GET"]; ok {

        t.handlers["GET"][path] = h
    } else {
        t.handlers["GET"] = make(map[string]Handler)
        t.handlers["GET"][path] = h
    }

}
func (t *Kevin) POST(path string, h Handler) {

    if _, ok := t.handlers["POST"]; ok {

        t.handlers["POST"][path] = h
    } else {
        t.handlers["POST"] = make(map[string]Handler)
        t.handlers["POST"][path] = h
    }
}
func (t *Kevin) DELETE(path string, h Handler) {

    if _, ok := t.handlers["DELETE"]; ok {

        t.handlers["DELETE"][path] = h
    } else {
        t.handlers["DELETE"] = make(map[string]Handler)
        t.handlers["DELETE"][path] = h
    }
}
func (t *Kevin) PUT(path string, h Handler) {

    if _, ok := t.handlers["PUT"]; ok {

        t.handlers["PUT"][path] = h
    } else {
        t.handlers["PUT"] = make(map[string]Handler)
        t.handlers["PUT"][path] = h
    }
}

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

    if h, ok := t.handlers[r.Method][r.RequestURI]; ok {

         h(&Context{w, r})
    } else {
        w.WriteHeader(404)
        w.Write([]byte("not found"))

    }

}

func (t *Kevin) Run(addr string) {

    err := http.ListenAndServe(addr, t)

    if err != nil {
        log.Fatal(err)
        panic(err)
    }

}

测试

package main

func main() {

    r := NewKevin()

    r.GET("/todo", func(ctx *Context) {

        ctx.ResponseWriter.Write([]byte("todo"))

    })

    r.Run(":8080")

}

ps,好了,暂时这样,比上一个看起来,稍微舒服些了,纯属给我媳妇顿修演示,里边逻辑不严谨的地方暂时不考虑

上一篇 下一篇

猜你喜欢

热点阅读