github.com/roblesoft/oak@v0.0.0-20230306162712-e6c5c487469e/router.go (about)

     1  package oak
     2  
     3  import (
     4  	"log"
     5  	"net/http"
     6  )
     7  
     8  type Router struct {
     9  	logger   *log.Logger
    10  	trees    map[string]*node
    11  	NotFound http.Handler
    12  }
    13  
    14  type Handle func(http.ResponseWriter, *http.Request)
    15  
    16  func (o *Router) Handler(handler http.HandlerFunc) Handle {
    17  	return func(w http.ResponseWriter, r *http.Request) {
    18  		handler.ServeHTTP(w, r)
    19  	}
    20  }
    21  
    22  func (o *Router) Handle(method string, path string, handler http.HandlerFunc) {
    23  	if o.trees == nil {
    24  		o.trees = make(map[string]*node)
    25  	}
    26  
    27  	if o.trees[method] != nil {
    28  		root := o.trees[method]
    29  		for len(root.children) != 0 {
    30  			root = root.children[0]
    31  		}
    32  		root.children = append(root.children,
    33  			&node{
    34  				method:  method,
    35  				path:    path,
    36  				handler: o.Handler(handler),
    37  			})
    38  	} else {
    39  		o.trees[method] = &node{
    40  			method:  method,
    41  			path:    path,
    42  			handler: o.Handler(handler),
    43  		}
    44  	}
    45  }
    46  
    47  func (o *Router) GET(path string, handlerFn http.HandlerFunc) {
    48  	o.Handle(http.MethodGet, path, handlerFn)
    49  }
    50  
    51  func (o *Router) POST(path string, handlerFn http.HandlerFunc) {
    52  	o.Handle(http.MethodPost, path, handlerFn)
    53  }
    54  
    55  func (o *Router) PUT(path string, handlerFn http.HandlerFunc) {
    56  	o.Handle(http.MethodPut, path, handlerFn)
    57  }
    58  
    59  func (o *Router) DELETE(path string, handlerFn http.HandlerFunc) {
    60  	o.Handle(http.MethodDelete, path, handlerFn)
    61  }
    62  
    63  func (o *Router) HEAD(path string, handlerFn http.HandlerFunc) {
    64  	o.Handle(http.MethodHead, path, handlerFn)
    65  }
    66  
    67  func (o *Router) PATCH(path string, handlerFn http.HandlerFunc) {
    68  	o.Handle(http.MethodPatch, path, handlerFn)
    69  }
    70  
    71  func (o *Router) OPTIONS(path string, handlerFn http.HandlerFunc) {
    72  	o.Handle(http.MethodOptions, path, handlerFn)
    73  }
    74  
    75  // ServeHTTP to implement http.Handler interface
    76  func (o *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    77  	o.logger.Println(req.Method, req.URL.Path)
    78  	path := req.URL.Path
    79  	root := o.trees[req.Method]
    80  
    81  	// handle not found
    82  	if root != nil {
    83  		root = root.getNode(path)
    84  	}
    85  
    86  	if root != nil {
    87  		root.getValue()(w, req)
    88  		return
    89  	}
    90  
    91  	http.NotFound(w, req)
    92  }