|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net/http" |
| 6 | + "net/http/httputil" |
| 7 | + "net/url" |
| 8 | + "os" |
| 9 | + |
| 10 | + "github.com/gin-gonic/gin" |
| 11 | +) |
| 12 | + |
| 13 | +// Routes |
| 14 | +const ( |
| 15 | + ServicesRoot = "/services" |
| 16 | + ServiceRoot = ServicesRoot + "/:name/*" + Wildcard |
| 17 | +) |
| 18 | + |
| 19 | +// serviceRoutes name to route map. |
| 20 | +var serviceRoutes = map[string]string{ |
| 21 | + "kai": os.Getenv("KAI_URL"), |
| 22 | +} |
| 23 | + |
| 24 | +// ServiceHandler handles service routes. |
| 25 | +type ServiceHandler struct { |
| 26 | + BaseHandler |
| 27 | +} |
| 28 | + |
| 29 | +// AddRoutes adds routes. |
| 30 | +func (h ServiceHandler) AddRoutes(e *gin.Engine) { |
| 31 | + e.GET(ServicesRoot, h.List) |
| 32 | + e.Any(ServiceRoot, h.Required, h.Forward) |
| 33 | +} |
| 34 | + |
| 35 | +// List godoc |
| 36 | +// @summary List named service routes. |
| 37 | +// @description List named service routes. |
| 38 | +// @tags services |
| 39 | +// @produce json |
| 40 | +// @success 200 {object} api.Service |
| 41 | +// @router /services [get] |
| 42 | +func (h ServiceHandler) List(ctx *gin.Context) { |
| 43 | + var r []Service |
| 44 | + for name, route := range serviceRoutes { |
| 45 | + service := Service{Name: name, Route: route} |
| 46 | + r = append(r, service) |
| 47 | + } |
| 48 | + |
| 49 | + h.Respond(ctx, http.StatusOK, r) |
| 50 | +} |
| 51 | + |
| 52 | +// Required enforces RBAC. |
| 53 | +func (h ServiceHandler) Required(ctx *gin.Context) { |
| 54 | + Required(ctx.Param(Name))(ctx) |
| 55 | +} |
| 56 | + |
| 57 | +// Forward provides RBAC and forwards request to the service. |
| 58 | +func (h ServiceHandler) Forward(ctx *gin.Context) { |
| 59 | + path := ctx.Param(Wildcard) |
| 60 | + name := ctx.Param(Name) |
| 61 | + route, found := serviceRoutes[name] |
| 62 | + if !found { |
| 63 | + err := &NotFound{Resource: name} |
| 64 | + _ = ctx.Error(err) |
| 65 | + return |
| 66 | + } |
| 67 | + if route == "" { |
| 68 | + err := fmt.Errorf("route for: '%s' not defined", name) |
| 69 | + _ = ctx.Error(err) |
| 70 | + return |
| 71 | + } |
| 72 | + u, err := url.Parse(route) |
| 73 | + if err != nil { |
| 74 | + err = &BadRequestError{Reason: err.Error()} |
| 75 | + _ = ctx.Error(err) |
| 76 | + return |
| 77 | + } |
| 78 | + proxy := httputil.ReverseProxy{ |
| 79 | + Director: func(req *http.Request) { |
| 80 | + req.URL.Scheme = u.Scheme |
| 81 | + req.URL.Host = u.Host |
| 82 | + req.URL.Path = path |
| 83 | + Log.Info( |
| 84 | + "Routing (service)", |
| 85 | + "path", |
| 86 | + ctx.Request.URL.Path, |
| 87 | + "route", |
| 88 | + req.URL.String()) |
| 89 | + }, |
| 90 | + } |
| 91 | + |
| 92 | + proxy.ServeHTTP(ctx.Writer, ctx.Request) |
| 93 | +} |
| 94 | + |
| 95 | +// Service REST resource. |
| 96 | +type Service struct { |
| 97 | + Name string `json:"name"` |
| 98 | + Route string `json:"route"` |
| 99 | +} |
0 commit comments