Brijesh's Git Server — toolkit @ 07f7705d52a615e47c3440f848a64abd85da22b1

my attempt at building my own web framework so I feel more confident when using chi

router/router.go (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
package router

import (
	"net/http"

	"brijesh.dev/toolkit/middleware"
)

type router struct {
	mux        *http.ServeMux
	middleware []middleware.Middleware
}

func NewRouter() *router {
	return &router{
		mux:        http.NewServeMux(),
		middleware: []middleware.Middleware{},
	}
}

func (r *router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	finalHandler := http.Handler(r.mux)
	for i := len(r.middleware) - 1; i >= 0; i-- {
		finalHandler = r.middleware[i](finalHandler)
	}
	finalHandler.ServeHTTP(w, req)
}

func (r *router) Use(mw middleware.Middleware) {
	r.middleware = append(r.middleware, mw)
}

func (r *router) Handle(method, pattern string, handler http.HandlerFunc) {
	r.mux.HandleFunc(pattern, func(w http.ResponseWriter, req *http.Request) {
		if req.Method != method {
			w.WriteHeader(http.StatusMethodNotAllowed)
			return
		}
		handler(w, req)
	})
}

func (r *router) GET(pattern string, handler http.HandlerFunc) {
	r.Handle(http.MethodGet, pattern, handler)
}

func (r *router) POST(pattern string, handler http.HandlerFunc) {
	r.Handle(http.MethodPost, pattern, handler)
}

func (r *router) PUT(pattern string, handler http.HandlerFunc) {
	r.Handle(http.MethodPut, pattern, handler)
}

func (r *router) DELETE(pattern string, handler http.HandlerFunc) {
	r.Handle(http.MethodDelete, pattern, handler)
}

func (r *router) PATCH(pattern string, handler http.HandlerFunc) {
	r.Handle(http.MethodPatch, pattern, handler)
}

func (r *router) HEAD(pattern string, handler http.HandlerFunc) {
	r.Handle(http.MethodHead, pattern, handler)
}

func (r *router) OPTIONS(pattern string, handler http.HandlerFunc) {
	r.Handle(http.MethodOptions, pattern, handler)
}

func (r *router) CONNECT(pattern string, handler http.HandlerFunc) {
	r.Handle(http.MethodConnect, pattern, handler)
}

func (r *router) TRACE(pattern string, handler http.HandlerFunc) {
	r.Handle(http.MethodTrace, pattern, handler)
}