|
| 1 | +package mux |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "strings" |
| 6 | + |
| 7 | + "github.com/DavidCai1993/routing" |
| 8 | + "github.com/go-http-utils/headers" |
| 9 | +) |
| 10 | + |
| 11 | +// Version is this package's version number. |
| 12 | +const Version = "0.0.1" |
| 13 | + |
| 14 | +// Handler responds to an HTTP request. |
| 15 | +type Handler interface { |
| 16 | + ServeHTTP(http.ResponseWriter, *http.Request, map[string]string) |
| 17 | +} |
| 18 | + |
| 19 | +// Mux is the HTTP request multiplexer. |
| 20 | +type Mux struct { |
| 21 | + root map[string]*routing.Node |
| 22 | +} |
| 23 | + |
| 24 | +// New returns a new mux. |
| 25 | +func New() *Mux { |
| 26 | + return &Mux{} |
| 27 | +} |
| 28 | + |
| 29 | +// Handle registers the handler for the given method and url. |
| 30 | +func (m *Mux) Handle(method string, url string, handler Handler) *Mux { |
| 31 | + if _, ok := m.root[method]; !ok { |
| 32 | + m.root[method] = routing.New() |
| 33 | + } |
| 34 | + |
| 35 | + m.root[method].Define(url, handler) |
| 36 | + |
| 37 | + return m |
| 38 | +} |
| 39 | + |
| 40 | +func (m Mux) ServeHTTP(res http.ResponseWriter, req *http.Request) { |
| 41 | + uri := req.RequestURI |
| 42 | + method := req.Method |
| 43 | + |
| 44 | + if method == http.MethodOptions { |
| 45 | + allows := []string{} |
| 46 | + res.WriteHeader(http.StatusNoContent) |
| 47 | + |
| 48 | + for m, n := range m.root { |
| 49 | + if _, _, ok := n.Match(uri); ok { |
| 50 | + allows = append(allows, m) |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + res.Header().Add(headers.Allow, strings.Join(allows, ", ")) |
| 55 | + |
| 56 | + return |
| 57 | + } |
| 58 | + |
| 59 | + if method == http.MethodHead { |
| 60 | + method = http.MethodGet |
| 61 | + } |
| 62 | + |
| 63 | + node, ok := m.root[method] |
| 64 | + |
| 65 | + if !ok { |
| 66 | + res.WriteHeader(http.StatusMethodNotAllowed) |
| 67 | + res.Write([]byte(http.StatusText(http.StatusMethodNotAllowed))) |
| 68 | + |
| 69 | + return |
| 70 | + } |
| 71 | + |
| 72 | + handler, params, ok := node.Match(uri) |
| 73 | + |
| 74 | + if !ok { |
| 75 | + res.WriteHeader(http.StatusNotFound) |
| 76 | + res.Write([]byte(http.StatusText(http.StatusNotFound))) |
| 77 | + |
| 78 | + return |
| 79 | + } |
| 80 | + |
| 81 | + handler.(Handler).ServeHTTP(res, req, params) |
| 82 | +} |
0 commit comments