ip.go 510 B

1234567891011121314151617181920212223242526272829303132
  1. package ip
  2. import (
  3. "encoding/json"
  4. "io"
  5. "net/http"
  6. )
  7. var ip string
  8. func GetIp() string {
  9. if ip != "" {
  10. return ip
  11. }
  12. resp, err := http.Get("http://ip-api.com/json/?lang=zh-CN ")
  13. if err != nil {
  14. return "[Your Server IP]"
  15. }
  16. defer resp.Body.Close()
  17. if resp.StatusCode == 200 {
  18. body, err := io.ReadAll(resp.Body)
  19. if err == nil {
  20. var queryRes map[string]string
  21. _ = json.Unmarshal(body, &queryRes)
  22. ip = queryRes["query"]
  23. return queryRes["query"]
  24. }
  25. }
  26. return "[Your Server IP]"
  27. }