page_index.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package page_index
  2. import (
  3. "encoding/json"
  4. "html/template"
  5. "net/http"
  6. "strings"
  7. "github.com/vladimirok5959/golang-ip2location/internal/consts"
  8. "github.com/vladimirok5959/golang-ip2location/internal/server/handler/base"
  9. "github.com/vladimirok5959/golang-ip2location/internal/server/web"
  10. "github.com/vladimirok5959/golang-utils/utils/http/helpers"
  11. "github.com/vladimirok5959/golang-utils/utils/http/render"
  12. )
  13. type Handler struct {
  14. base.Handler
  15. }
  16. func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  17. data := &base.ServerData{
  18. URL: r.URL.Path,
  19. WebURL: consts.Config.WebURL,
  20. }
  21. var additional struct {
  22. ClientIP string
  23. GeoIPData template.HTML
  24. }
  25. additional.ClientIP = helpers.ClientIP(r)
  26. ip := strings.Trim(r.FormValue("ip"), " ")
  27. if ip != "" && len([]rune(ip)) <= 15 {
  28. additional.ClientIP = ip
  29. }
  30. if h.Client != nil {
  31. if res, err := h.Client.IP2Location(r.Context(), additional.ClientIP); err == nil {
  32. if j, err := json.Marshal(res); err == nil {
  33. additional.GeoIPData = template.HTML(string(j))
  34. }
  35. }
  36. }
  37. data.Additional = additional
  38. if !render.HTML(w, r, h.FuncMap(w, r), data, web.IndexHtml, http.StatusOK) {
  39. return
  40. }
  41. }