page_index.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. AppVersion: consts.AppVersion,
  19. AssetsVersion: consts.AssetsVersion,
  20. URL: r.URL.Path,
  21. WebURL: consts.Config.WebURL,
  22. }
  23. var additional struct {
  24. ClientIP string
  25. GeoIPData template.HTML
  26. }
  27. additional.ClientIP = helpers.ClientIP(r)
  28. ip := strings.Trim(r.FormValue("ip"), " ")
  29. if ip != "" && len([]rune(ip)) <= 15 {
  30. additional.ClientIP = ip
  31. }
  32. if h.Client != nil {
  33. if res, err := h.Client.IP2Location(r.Context(), additional.ClientIP); err == nil {
  34. if j, err := json.MarshalIndent(res, "<br>", "&nbsp;&nbsp;"); err == nil {
  35. additional.GeoIPData = template.HTML(string(j))
  36. }
  37. }
  38. }
  39. data.Additional = additional
  40. if !render.HTML(w, r, h.FuncMap(w, r), data, web.IndexHtml, http.StatusOK) {
  41. return
  42. }
  43. }