|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "log" |
| 6 | + "sync" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/gin-gonic/gin" |
| 10 | +) |
| 11 | + |
| 12 | +type API interface { |
| 13 | + Start() error |
| 14 | + AddRoute(method, path string, handler gin.HandlerFunc) |
| 15 | +} |
| 16 | + |
| 17 | +type APIv1 struct { |
| 18 | + engine *gin.Engine |
| 19 | + apiGroup *gin.RouterGroup |
| 20 | + host string |
| 21 | + port string |
| 22 | +} |
| 23 | + |
| 24 | +type APIRouteRegistrar interface { |
| 25 | + RegisterRoutes() |
| 26 | +} |
| 27 | + |
| 28 | +type APIOption func(*APIv1) |
| 29 | + |
| 30 | +func WithGroup(group string) APIOption { |
| 31 | + // Expects '/v1' as the group |
| 32 | + return func(a *APIv1) { |
| 33 | + a.apiGroup = a.engine.Group(group) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +func WithHost(host string) APIOption { |
| 38 | + return func(a *APIv1) { |
| 39 | + a.host = host |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +func WithPort(port string) APIOption { |
| 44 | + return func(a *APIv1) { |
| 45 | + a.port = port |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +var apiInstance *APIv1 |
| 50 | +var once sync.Once |
| 51 | + |
| 52 | +func NewAPI(debug bool, options ...APIOption) *APIv1 { |
| 53 | + once.Do(func() { |
| 54 | + apiInstance = &APIv1{ |
| 55 | + engine: ConfigureRouter(debug), |
| 56 | + host: "localhost", |
| 57 | + port: "8080", |
| 58 | + } |
| 59 | + for _, opt := range options { |
| 60 | + opt(apiInstance) |
| 61 | + } |
| 62 | + }) |
| 63 | + return apiInstance |
| 64 | +} |
| 65 | + |
| 66 | +func GetInstance() *APIv1 { |
| 67 | + return apiInstance |
| 68 | +} |
| 69 | + |
| 70 | +func (a *APIv1) Engine() *gin.Engine { |
| 71 | + return a.engine |
| 72 | +} |
| 73 | + |
| 74 | +func (a *APIv1) Start() error { |
| 75 | + address := a.host + ":" + a.port |
| 76 | + // Use buffered channel to not block goroutine |
| 77 | + errChan := make(chan error, 1) |
| 78 | + |
| 79 | + go func() { |
| 80 | + // Capture the error returned by Run |
| 81 | + errChan <- a.engine.Run(address) |
| 82 | + }() |
| 83 | + |
| 84 | + select { |
| 85 | + case err := <-errChan: |
| 86 | + return err |
| 87 | + default: |
| 88 | + // No starting errors, start server |
| 89 | + } |
| 90 | + |
| 91 | + return nil |
| 92 | +} |
| 93 | + |
| 94 | +func (a *APIv1) AddRoute(method, path string, handler gin.HandlerFunc) { |
| 95 | + // Inner function to add routes to a given target |
| 96 | + //(either gin.Engine or gin.RouterGroup) |
| 97 | + addRouteToTarget := func(target gin.IRoutes) { |
| 98 | + switch method { |
| 99 | + case "GET": |
| 100 | + target.GET(path, handler) |
| 101 | + case "POST": |
| 102 | + target.POST(path, handler) |
| 103 | + case "PUT": |
| 104 | + target.PUT(path, handler) |
| 105 | + case "DELETE": |
| 106 | + target.DELETE(path, handler) |
| 107 | + case "PATCH": |
| 108 | + target.PATCH(path, handler) |
| 109 | + case "HEAD": |
| 110 | + target.HEAD(path, handler) |
| 111 | + case "OPTIONS": |
| 112 | + target.OPTIONS(path, handler) |
| 113 | + default: |
| 114 | + log.Printf("Unsupported HTTP method: %s", method) |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + // Check if a specific apiGroup is set |
| 119 | + // If so, add the route to it. Otherwise, add to the main engine. |
| 120 | + if a.apiGroup != nil { |
| 121 | + addRouteToTarget(a.apiGroup) |
| 122 | + } else { |
| 123 | + addRouteToTarget(a.engine) |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +func ConfigureRouter(debug bool) *gin.Engine { |
| 128 | + if !debug { |
| 129 | + gin.SetMode(gin.ReleaseMode) |
| 130 | + } |
| 131 | + gin.DisableConsoleColor() |
| 132 | + g := gin.New() |
| 133 | + g.Use(gin.Recovery()) |
| 134 | + // Custom access logging |
| 135 | + g.Use(gin.LoggerWithFormatter(accessLogger)) |
| 136 | + // Healthcheck endpoint |
| 137 | + g.GET("/healthcheck", handleHealthcheck) |
| 138 | + // No-op API endpoint for testing |
| 139 | + g.GET("/ping", func(c *gin.Context) { |
| 140 | + c.String(200, "pong") |
| 141 | + }) |
| 142 | + // Swagger UI |
| 143 | + // TODO: add swagger UI |
| 144 | + // g.Static("/swagger-ui", "swagger-ui") |
| 145 | + return g |
| 146 | +} |
| 147 | + |
| 148 | +func accessLogger(param gin.LogFormatterParams) string { |
| 149 | + logEntry := gin.H{ |
| 150 | + "type": "access", |
| 151 | + "client_ip": param.ClientIP, |
| 152 | + "timestamp": param.TimeStamp.Format(time.RFC1123), |
| 153 | + "method": param.Method, |
| 154 | + "path": param.Path, |
| 155 | + "proto": param.Request.Proto, |
| 156 | + "status_code": param.StatusCode, |
| 157 | + "latency": param.Latency, |
| 158 | + "user_agent": param.Request.UserAgent(), |
| 159 | + "error_message": param.ErrorMessage, |
| 160 | + } |
| 161 | + ret, _ := json.Marshal(logEntry) |
| 162 | + return string(ret) + "\n" |
| 163 | +} |
| 164 | + |
| 165 | +func handleHealthcheck(c *gin.Context) { |
| 166 | + // TODO: add some actual health checking here |
| 167 | + c.JSON(200, gin.H{"failed": false}) |
| 168 | +} |
0 commit comments