feat(api): allow listening with unix socket
This commit is contained in:
parent
ebbd49cce5
commit
c4c5c49239
1 changed files with 52 additions and 9 deletions
45
api/main.go
45
api/main.go
|
@ -1,13 +1,17 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
|
@ -31,6 +35,7 @@ type serverConfig struct {
|
|||
CityDB string
|
||||
Listen string
|
||||
Mode string
|
||||
SocketPermission fs.FileMode
|
||||
}
|
||||
|
||||
type body struct {
|
||||
|
@ -47,10 +52,16 @@ type bodyError struct {
|
|||
}
|
||||
|
||||
func main() {
|
||||
perm, err := strconv.ParseUint(getEnvOr("IP_CHECKER_SOCKET_PERMISSION", "0600"), 8, 32)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
config = serverConfig{
|
||||
ASNDB: os.Getenv("IP_CHECKER_ASN_DB"),
|
||||
CityDB: os.Getenv("IP_CHECKER_CITY_DB"),
|
||||
Listen: getEnvOr("IP_CHECKER_LISTEN", ":8080"),
|
||||
SocketPermission: fs.FileMode(perm),
|
||||
Mode: os.Getenv("IP_CHECKER_MODE"),
|
||||
}
|
||||
|
||||
|
@ -76,8 +87,40 @@ func main() {
|
|||
}
|
||||
|
||||
http.HandleFunc("/api/v1/ip", handleRequest)
|
||||
|
||||
log.Printf("Starting server on %s", config.Listen)
|
||||
log.Fatal(http.ListenAndServe(config.Listen, nil))
|
||||
|
||||
var srv http.Server
|
||||
|
||||
// graceful shutdown
|
||||
go func() {
|
||||
sigint := make(chan os.Signal, 1)
|
||||
signal.Notify(sigint, os.Interrupt)
|
||||
<-sigint
|
||||
|
||||
srv.Shutdown(context.Background())
|
||||
}()
|
||||
|
||||
if strings.HasPrefix(config.Listen, "unix/") {
|
||||
socketPath := strings.TrimPrefix(config.Listen, "unix/")
|
||||
unixListener, err := net.Listen("unix", socketPath)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
if err := os.Chmod(socketPath, config.SocketPermission); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
if err := srv.Serve(unixListener); err != http.ErrServerClosed {
|
||||
log.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
srv.Addr = config.Listen
|
||||
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func generateJSON(ip string) (body, error) {
|
||||
|
|
Loading…
Reference in a new issue