|
| 1 | +Introduction |
| 2 | +============ |
| 3 | + |
| 4 | +This is an extremely minimal router, for usage in your own application. Supports only 2 things: |
| 5 | +* routing based on request-method and path |
| 6 | +* parameters in URLs |
| 7 | + |
| 8 | +I build it for a json-only REST api with a few routes. |
| 9 | + |
| 10 | +Usage |
| 11 | +===== |
| 12 | + |
| 13 | +This intentionally does NOT implement `ServeHTTP`, as you should implement this |
| 14 | +yourself, to do any wrapping and processing of request or response. |
| 15 | + |
| 16 | +Example |
| 17 | +======= |
| 18 | + |
| 19 | +```go |
| 20 | +package main |
| 21 | + |
| 22 | +import ( |
| 23 | + "encoding/json" |
| 24 | + "github.com/parse-nl/MinimalRouter" |
| 25 | + "net/http" |
| 26 | +) |
| 27 | + |
| 28 | +type appController struct{} |
| 29 | +type appRequest struct{ Params map[string]string } |
| 30 | +type appResponse struct{ Result string } |
| 31 | + |
| 32 | +var router *minimalrouter.Router |
| 33 | + |
| 34 | +func init() { |
| 35 | + router = minimalrouter.New() |
| 36 | + |
| 37 | + router.Add("GET", "/ping", handleGetPing) |
| 38 | + router.Add("POST", "/hello-from/:name", handlePostHello) |
| 39 | +} |
| 40 | + |
| 41 | +func main() { |
| 42 | + http.ListenAndServe(":8088", &appController{}) |
| 43 | +} |
| 44 | + |
| 45 | +// implement the standard ServeHTTP as required by golang |
| 46 | +// handles json encoding and decoding, could implement authentication as well |
| 47 | +func (c *appController) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 48 | + var result *appResponse |
| 49 | + |
| 50 | + fn, params := router.Match(r.Method, r.URL.Path) |
| 51 | + request := &appRequest{params} |
| 52 | + |
| 53 | + if fn == nil { |
| 54 | + w.WriteHeader(http.StatusNotFound) |
| 55 | + result = &appResponse{"error"} |
| 56 | + } else { |
| 57 | + w.WriteHeader(http.StatusOK) |
| 58 | + |
| 59 | + // convert the generic interface{} to the function-signature we expect |
| 60 | + result = fn.(func(*appRequest) *appResponse)(request) |
| 61 | + } |
| 62 | + |
| 63 | + w.Header().Add("Content-Type", "application/json") |
| 64 | + enc := json.NewEncoder(w) |
| 65 | + enc.Encode(result) |
| 66 | +} |
| 67 | + |
| 68 | +func handleGetPing(r *appRequest) *appResponse { |
| 69 | + return &appResponse{"pong"} |
| 70 | +} |
| 71 | + |
| 72 | +func handlePostHello(r *appRequest) *appResponse { |
| 73 | + return &appResponse{"hey " + r.Params["name"]} |
| 74 | +} |
| 75 | + |
| 76 | +``` |
0 commit comments