added flexible socket/tcp listen

This commit is contained in:
Giovanni Harting 2023-12-14 17:18:38 +01:00
parent 908fa9b2e5
commit 5bbf0add35
2 changed files with 63 additions and 1 deletions

51
main.go
View File

@ -5,6 +5,7 @@ import (
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"flag"
"fmt"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/render"
@ -12,6 +13,7 @@ import (
log "github.com/sirupsen/logrus"
"github.com/wercker/journalhook"
"gopkg.in/yaml.v3"
"net"
"net/http"
"os"
"os/signal"
@ -89,7 +91,50 @@ func main() {
// routes
r.Get("/stats", GetStats)
r.Get("/packages", GetPackages)
log.Fatal(http.ListenAndServe(":3043", r))
log.Info("Start listening...")
sockets := make([]net.Listener, 0)
for _, l := range conf.Httpd.Listen {
if l.Socket != "" {
sL, err := net.Listen("unix", l.Socket)
log.Infof("Listening on %s", l.Socket)
if err != nil {
log.Panicf("Failure listing on socket %s: %v", l.Socket, err)
}
sockets = append(sockets, sL)
go func() {
srv := &http.Server{
ReadTimeout: time.Duration(conf.Httpd.Timeout.Read) * time.Second,
WriteTimeout: time.Duration(conf.Httpd.Timeout.Write) * time.Second,
IdleTimeout: time.Duration(conf.Httpd.Timeout.Idle) * time.Second,
Handler: r,
}
_ = srv.Serve(sL)
}()
} else {
log.Infof("Listening on %s:%d", l.Host, l.Port)
tL, err := net.Listen("tcp", fmt.Sprintf("%s:%d", l.Host, l.Port))
if err != nil {
log.Panicf("Failure listing on %s:%d: %v", l.Host, l.Port, err)
}
go func(l struct {
Socket string
Host string
Port int
}) {
srv := &http.Server{
ReadTimeout: time.Duration(conf.Httpd.Timeout.Read) * time.Second,
WriteTimeout: time.Duration(conf.Httpd.Timeout.Write) * time.Second,
IdleTimeout: time.Duration(conf.Httpd.Timeout.Idle) * time.Second,
Handler: r,
}
err = srv.Serve(tL)
if err != nil {
log.Fatalf("Failure serving on %s:%d: %v", l.Host, l.Port, err)
}
}(l)
}
}
killLoop:
for {
@ -115,4 +160,8 @@ killLoop:
log.Infof("config reloaded")
}
}
for _, s := range sockets {
_ = s.Close()
}
}

View File

@ -8,4 +8,17 @@ type Conf struct {
Logging struct {
Level string
}
Httpd struct {
CORSAllowDomains []string `yaml:"cors_allow_domains"`
Listen []struct {
Socket string
Host string
Port int
}
Timeout struct {
Read int
Write int
Idle int
}
}
}