| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- package handler
- import (
- "net/http"
- "goflare/internal/database/queries"
- "goflare/internal/ipfetcher"
- "github.com/labstack/echo/v4"
- )
- type IPHandler struct {
- q *queries.Queries
- }
- func NewIPHandler(q *queries.Queries) *IPHandler {
- return &IPHandler{q: q}
- }
- const (
- settingKeyCurrentIP = "current_ip"
- settingKeyCurrentIPUpdatedAt = "current_ip_updated_at"
- )
- func (h *IPHandler) Get(c echo.Context) error {
- ctx := c.Request().Context()
- cached, err := h.q.GetSetting(ctx, settingKeyCurrentIP)
- if err == nil && cached != "" {
- resp := map[string]string{"ip": cached}
- if updatedAt, err := h.q.GetSetting(ctx, settingKeyCurrentIPUpdatedAt); err == nil && updatedAt != "" {
- resp["ip_updated_at"] = updatedAt
- }
- return c.JSON(http.StatusOK, resp)
- }
- urls, err := h.q.ListEnabledIpProviderUrls(ctx)
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to load IP providers"})
- }
- var urlsOrNil []string
- if len(urls) > 0 {
- urlsOrNil = urls
- }
- ip, err := ipfetcher.FetchPublicIPFrom(ctx, urlsOrNil)
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to fetch public IP"})
- }
- return c.JSON(http.StatusOK, map[string]string{"ip": ip})
- }
|