package routers import ( "context" "fmt" "log" "net/http" "strconv" "git.paulbsd.com/paulbsd/ipbl/src/config" "git.paulbsd.com/paulbsd/ipbl/src/models" "github.com/labstack/echo/v4" ) // RegisterRoutes runs the main echo HTTP server func RegisterRoutes(e *echo.Echo, ctx *context.Context, cfg *config.Config) { e.GET("/", func(c echo.Context) error { return c.HTML(http.StatusOK, `
Welcome to ipbl software (https://git.paulbsd.com/paulbsd/ipbl)
`) }) // IPs e.GET("/ip/:ip", func(c echo.Context) (err error) { ret, err := models.GetIP(ctx, cfg, c.Param("ip")) return JSONResult(c, err, ret) }) e.POST("/ip", func(c echo.Context) (err error) { var ip = new(models.IP) var msg string err = c.Bind(ip) if err != nil { return JSONResult(c, fmt.Errorf("Error when parsing body"), "") } num, err := ip.InsertIP(cfg) if err != nil { return JSONResult(c, fmt.Errorf("Error inserting data"), "") } if num > 0 { msg = fmt.Sprintf("Inserted %d IP", num) } return c.JSON(http.StatusOK, msg) }) e.GET("/ips", func(c echo.Context) (err error) { limit := 50 if c.QueryParam("limit") != "" { limit, _ = strconv.Atoi(c.QueryParam("limit")) } ret, err := models.GetIPs(ctx, cfg, limit) return JSONResult(c, err, ret) }) e.GET("/ips/lastday", func(c echo.Context) (err error) { interval := "1 day" ret, err := models.GetIPsLastDay(ctx, cfg, interval) return JSONResult(c, err, ret) }) e.POST("/ips", func(c echo.Context) (err error) { var ips = []models.IP{} var msg string err = c.Bind(&ips) if err != nil { return c.JSON(http.StatusInternalServerError, "Error when parsing body") } numinsert, numupdate, _, _ := models.InsertIPBulk(cfg, &ips) if numinsert > 0 { msg = fmt.Sprintf("Inserted %d IP", numinsert) log.Println(msg) } if numupdate > 0 { msg = fmt.Sprintf("Updated %d IP", numupdate) log.Println(msg) } return c.JSON(http.StatusOK, msg) }) e.GET("/ips/whitelist", func(c echo.Context) (err error) { var whitelists = models.GetWhitelists(*cfg) if len(whitelists) > 0 { return c.JSON(http.StatusOK, whitelists) } return c.JSON(http.StatusInternalServerError, "") }) e.Logger.Fatal( e.Start( fmt.Sprintf(":%d", cfg.Switchs.Port))) }