This commit is contained in:
parent
e009b52c7b
commit
b66129d29c
6
internal/pkg/response/response.go
Normal file
6
internal/pkg/response/response.go
Normal file
@ -0,0 +1,6 @@
|
||||
package response
|
||||
|
||||
type MyIPResponse struct {
|
||||
Address string `json:"address"`
|
||||
Version string `json:"version"`
|
||||
}
|
25
internal/pkg/utils/network.go
Normal file
25
internal/pkg/utils/network.go
Normal 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")
|
||||
}
|
||||
}
|
@ -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)
|
||||
|
@ -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),
|
||||
})
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user