ip.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package handler
  2. import (
  3. "net/http"
  4. "goflare/internal/database/queries"
  5. "goflare/internal/ipfetcher"
  6. "github.com/labstack/echo/v4"
  7. )
  8. type IPHandler struct {
  9. q *queries.Queries
  10. }
  11. func NewIPHandler(q *queries.Queries) *IPHandler {
  12. return &IPHandler{q: q}
  13. }
  14. const settingKeyCurrentIP = "current_ip"
  15. func (h *IPHandler) Get(c echo.Context) error {
  16. ctx := c.Request().Context()
  17. cached, err := h.q.GetSetting(ctx, settingKeyCurrentIP)
  18. if err == nil && cached != "" {
  19. return c.JSON(http.StatusOK, map[string]string{"ip": cached})
  20. }
  21. urls, err := h.q.ListEnabledIpProviderUrls(ctx)
  22. if err != nil {
  23. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to load IP providers"})
  24. }
  25. var urlsOrNil []string
  26. if len(urls) > 0 {
  27. urlsOrNil = urls
  28. }
  29. ip, err := ipfetcher.FetchPublicIPFrom(ctx, urlsOrNil)
  30. if err != nil {
  31. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to fetch public IP"})
  32. }
  33. return c.JSON(http.StatusOK, map[string]string{"ip": ip})
  34. }