pref: update myip API
All checks were successful
CI / deploy (push) Successful in 2m27s

This commit is contained in:
thehrz 2024-08-18 23:23:18 +08:00
parent e009b52c7b
commit b66129d29c
Signed by: thehrz
GPG Key ID: C84CBCE7D5F88855
4 changed files with 43 additions and 1 deletions

View File

@ -0,0 +1,6 @@
package response
type MyIPResponse struct {
Address string `json:"address"`
Version string `json:"version"`
}

View File

@ -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")
}
}

View File

@ -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)

View File

@ -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),
})
}