44 lines
801 B
Go
44 lines
801 B
Go
package api
|
|
|
|
import (
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/rs/zerolog/log"
|
|
"net"
|
|
"net/http"
|
|
"thuanle.me/ip-info/internal/data"
|
|
)
|
|
|
|
func HandleJson(c *gin.Context) {
|
|
ip := c.ClientIP()
|
|
HandleIpInfo(c, ip)
|
|
}
|
|
|
|
func HandleOtherIp(c *gin.Context) {
|
|
ip := c.Param("ip")
|
|
if net.ParseIP(ip) == nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ip"})
|
|
return
|
|
}
|
|
HandleIpInfo(c, ip)
|
|
}
|
|
|
|
func HandleIpInfo(c *gin.Context, ip string) {
|
|
if !data.Ins().IsLoaded() {
|
|
log.Error().Msg("DB is not loaded")
|
|
c.String(http.StatusInternalServerError, "Try again later")
|
|
return
|
|
}
|
|
|
|
ipData, _, err := data.Ins().Query(ip)
|
|
if err != nil {
|
|
log.Err(err).Msg("Failed to query IP")
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"ip": ip,
|
|
})
|
|
return
|
|
}
|
|
|
|
ipData["ip"] = ip
|
|
c.JSON(http.StatusOK, ipData)
|
|
}
|