|
| 1 | +package controllers |
| 2 | + |
| 3 | +import ( |
| 4 | + "strconv" |
| 5 | + |
| 6 | + "github.com/FoxComm/highlander/remote/responses" |
| 7 | + "github.com/labstack/echo" |
| 8 | +) |
| 9 | + |
| 10 | +// FoxContext is a wrapper around echo.Context that eases error handling, |
| 11 | +// provides helper methods, and ensures we have consistent response handling. |
| 12 | +type FoxContext struct { |
| 13 | + echo.Context |
| 14 | + resp *responses.Response |
| 15 | +} |
| 16 | + |
| 17 | +// NewFoxContext creates a new FoxContext from an existing echo.Context. |
| 18 | +func NewFoxContext(c echo.Context) *FoxContext { |
| 19 | + return &FoxContext{c, nil} |
| 20 | +} |
| 21 | + |
| 22 | +// ParamInt parses an integer from the parameters list (as defined by the URI). |
| 23 | +func (fc *FoxContext) ParamInt(name string) int { |
| 24 | + if fc.resp != nil { |
| 25 | + return 0 |
| 26 | + } |
| 27 | + |
| 28 | + param := fc.Param(name) |
| 29 | + if param == "" { |
| 30 | + fc.resp = errParamNotFound(name) |
| 31 | + return 0 |
| 32 | + } |
| 33 | + |
| 34 | + paramInt, err := strconv.Atoi(param) |
| 35 | + if err != nil { |
| 36 | + fc.resp = errParamMustBeNumber(name) |
| 37 | + return 0 |
| 38 | + } |
| 39 | + |
| 40 | + return paramInt |
| 41 | +} |
| 42 | + |
| 43 | +// ParamString parses an string from the parameters list (as defined by the URI). |
| 44 | +func (fc *FoxContext) ParamString(name string) string { |
| 45 | + if fc.resp != nil { |
| 46 | + return "" |
| 47 | + } |
| 48 | + |
| 49 | + param := fc.Param(name) |
| 50 | + if param == "" { |
| 51 | + fc.resp = errParamNotFound(name) |
| 52 | + return "" |
| 53 | + } |
| 54 | + |
| 55 | + return param |
| 56 | +} |
| 57 | + |
| 58 | +// Run executes the primary controller method and returns the response. |
| 59 | +func (fc *FoxContext) Run(ctrlFn ControllerFunc) error { |
| 60 | + if fc.resp != nil { |
| 61 | + return fc.handleResponse(fc.resp) |
| 62 | + } |
| 63 | + |
| 64 | + return fc.handleResponse(ctrlFn()) |
| 65 | +} |
| 66 | + |
| 67 | +func (fc *FoxContext) handleResponse(resp *responses.Response) error { |
| 68 | + if len(resp.Errs) == 0 { |
| 69 | + return fc.JSON(resp.StatusCode, resp.Body) |
| 70 | + } |
| 71 | + |
| 72 | + errors := make([]string, len(resp.Errs)) |
| 73 | + for i, err := range resp.Errs { |
| 74 | + errors[i] = err.Error() |
| 75 | + } |
| 76 | + |
| 77 | + errResp := map[string][]string{ |
| 78 | + "errors": errors, |
| 79 | + } |
| 80 | + |
| 81 | + return fc.JSON(resp.StatusCode, errResp) |
| 82 | +} |
0 commit comments