ip.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 (
  15. settingKeyCurrentIP = "current_ip"
  16. settingKeyCurrentIPUpdatedAt = "current_ip_updated_at"
  17. )
  18. func (h *IPHandler) Get(c echo.Context) error {
  19. ctx := c.Request().Context()
  20. cached, err := h.q.GetSetting(ctx, settingKeyCurrentIP)
  21. if err == nil && cached != "" {
  22. resp := map[string]string{"ip": cached}
  23. if updatedAt, err := h.q.GetSetting(ctx, settingKeyCurrentIPUpdatedAt); err == nil && updatedAt != "" {
  24. resp["ip_updated_at"] = updatedAt
  25. }
  26. return c.JSON(http.StatusOK, resp)
  27. }
  28. urls, err := h.q.ListEnabledIpProviderUrls(ctx)
  29. if err != nil {
  30. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to load IP providers"})
  31. }
  32. var urlsOrNil []string
  33. if len(urls) > 0 {
  34. urlsOrNil = urls
  35. }
  36. ip, err := ipfetcher.FetchPublicIPFrom(ctx, urlsOrNil)
  37. if err != nil {
  38. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to fetch public IP"})
  39. }
  40. return c.JSON(http.StatusOK, map[string]string{"ip": ip})
  41. }