first commit
This commit is contained in:
10
internal/services/api/handler_ip.go
Normal file
10
internal/services/api/handler_ip.go
Normal file
@@ -0,0 +1,10 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func HandleIp(c *gin.Context) {
|
||||
c.String(http.StatusOK, c.ClientIP())
|
||||
}
|
||||
19
internal/services/api/handler_json.go
Normal file
19
internal/services/api/handler_json.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/rs/zerolog/log"
|
||||
"net/http"
|
||||
"thuanle.me/ip-info/internal/data"
|
||||
)
|
||||
|
||||
func HandleJson(c *gin.Context) {
|
||||
ip := c.ClientIP()
|
||||
ipData, _, err := data.Ins().Query(ip)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("Failed to query IP")
|
||||
c.String(http.StatusInternalServerError, "")
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, ipData)
|
||||
}
|
||||
47
internal/services/api/main.go
Normal file
47
internal/services/api/main.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/rs/zerolog/log"
|
||||
"net/http"
|
||||
"os"
|
||||
"thuanle.me/ip-info/configs/key"
|
||||
)
|
||||
|
||||
var srv *http.Server
|
||||
|
||||
func StartApiService() {
|
||||
log.Info().Msg("Starting API service")
|
||||
|
||||
engine := gin.Default()
|
||||
|
||||
trustedProxyIP := os.Getenv(key.EnvGinTrustedProxyIp)
|
||||
if trustedProxyIP != "" {
|
||||
_ = engine.SetTrustedProxies([]string{trustedProxyIP})
|
||||
}
|
||||
|
||||
engine.GET("/", HandleIp)
|
||||
engine.GET("/json", HandleJson)
|
||||
|
||||
port := os.Getenv(key.EnvApiPort)
|
||||
srv = &http.Server{
|
||||
Addr: ":" + port,
|
||||
Handler: engine,
|
||||
}
|
||||
|
||||
go func() {
|
||||
// service connections
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Fatal().Err(err).Msg("Error running API service")
|
||||
}
|
||||
}()
|
||||
|
||||
log.Info().Str("port", port).Msg("API service started")
|
||||
|
||||
}
|
||||
|
||||
func Shutdown() {
|
||||
_ = srv.Close()
|
||||
log.Info().Msg("API service stopped")
|
||||
}
|
||||
Reference in New Issue
Block a user