52 lines
980 B
Go
52 lines
980 B
Go
package api
|
|
|
|
import (
|
|
"errors"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/rs/zerolog/log"
|
|
"net/http"
|
|
"os"
|
|
"thuanle.me/ip-info/configs"
|
|
"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)
|
|
if len(port) == 0 {
|
|
port = configs.ApiDefaultPort
|
|
}
|
|
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")
|
|
}
|