Exemplo n.º 1
0
func (mm *ModuleManager) RegisterRouterGroup(group *gin.RouterGroup) {
	group.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, (*mm).GetAllModules())
	})

	group.POST("/", func(c *gin.Context) {
		var req shared.Module
		err := c.BindJSON(&req)
		if err != nil {
			c.JSON(400, shared.HttpError{"Decoding HTTP body failed.", err})
			return
		}

		if strings.TrimSpace(req.ModuleURL) == "" {
			c.JSON(400, shared.HttpError{"Attribute 'module-url' is missing.", nil})
			return
		}

		if mm.GetModule(req.Metadata.ID) != nil {
			c.JSON(423, shared.HttpError{"Module already registered.", nil})
			return
		}

		mm.AddModule(&req)
	})

	group.Any("/:module/proxy/*path", func(c *gin.Context) {
		module := mm.GetModule(c.Param("module"))
		if module == nil {
			c.JSON(404, shared.HttpError{"Module not found.", nil})
			return
		}

		target, err := url.Parse(module.ModuleURL)
		if module == nil {
			c.JSON(500, shared.HttpError{"Error connecting to module.", err})
			return
		}

		oldPrefix := fmt.Sprintf("%s/%s/proxy", group.BasePath(), module.Metadata.ID)
		newPrefix := "/module"

		var handler http.Handler
		handler = httputil.NewSingleHostReverseProxy(target)
		handler = HTTPAddPrefix(newPrefix, handler)
		handler = http.StripPrefix(oldPrefix, handler)

		wrapper := gin.WrapH(handler)
		wrapper(c)
	})
}