From b66129d29c485274eb78cacd006efc8daeecd226 Mon Sep 17 00:00:00 2001 From: thehrz Date: Sun, 18 Aug 2024 23:23:18 +0800 Subject: [PATCH] pref: update myip API --- internal/pkg/response/response.go | 6 ++++++ internal/pkg/utils/network.go | 25 +++++++++++++++++++++++++ internal/router/router.go | 1 + internal/router/routes/ip/myip.go | 12 +++++++++++- 4 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 internal/pkg/response/response.go create mode 100644 internal/pkg/utils/network.go diff --git a/internal/pkg/response/response.go b/internal/pkg/response/response.go new file mode 100644 index 0000000..fc4a459 --- /dev/null +++ b/internal/pkg/response/response.go @@ -0,0 +1,6 @@ +package response + +type MyIPResponse struct { + Address string `json:"address"` + Version string `json:"version"` +} diff --git a/internal/pkg/utils/network.go b/internal/pkg/utils/network.go new file mode 100644 index 0000000..73e7f15 --- /dev/null +++ b/internal/pkg/utils/network.go @@ -0,0 +1,25 @@ +package utils + +import ( + "errors" + "net" +) + +const ( + IPv4 = 4 + IPv6 = 6 +) + +func GetIPVersion(ip string) (int, error) { + parsedIP := net.ParseIP(ip) + if parsedIP == nil { + return 0, errors.New("invalid IP address") + } + if parsedIP.To4() != nil { + return IPv4, nil + } else if parsedIP.To16() != nil { + return IPv6, nil + } else { + return 0, errors.New("invalid IP address") + } +} diff --git a/internal/router/router.go b/internal/router/router.go index 1b34176..7452272 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -8,6 +8,7 @@ import ( func Register() *gin.Engine { g := gin.New() g.Use(gin.Recovery()) + g.Use(gin.Logger()) ipGroup := g.Group("ip") ipGroup.GET("myip", ip.MyIP) diff --git a/internal/router/routes/ip/myip.go b/internal/router/routes/ip/myip.go index 714d26b..5e4b0f4 100644 --- a/internal/router/routes/ip/myip.go +++ b/internal/router/routes/ip/myip.go @@ -2,9 +2,19 @@ package ip import ( "github.com/gin-gonic/gin" + "ipv6-test-node/internal/pkg/response" + "ipv6-test-node/internal/pkg/utils" "net/http" + "strconv" ) func MyIP(c *gin.Context) { - c.JSON(http.StatusOK, c.ClientIP()) + version, err := utils.GetIPVersion(c.ClientIP()) + if err != nil { + return + } + c.JSON(http.StatusOK, response.MyIPResponse{ + Address: c.ClientIP(), + Version: strconv.Itoa(version), + }) }