Commit 6ad85c4
cmd/gtwy/main.go
@@ -6,11 +6,11 @@ import (
"net/http"
"net/http/httputil"
"strings"
- "time"
"github.com/casbin/casbin/v2"
"github.com/xlgmokha/x/pkg/env"
"github.com/xlgmokha/x/pkg/x"
+ "gitlab.com/mokhax/spike/pkg/srv"
)
func NewRouter(routes map[string]string) http.Handler {
@@ -48,21 +48,14 @@ func NewRouter(routes map[string]string) http.Handler {
func main() {
mux := http.NewServeMux()
- routes := map[string]string{
+ mux.Handle("/", NewRouter(map[string]string{
"idp.example.com": "localhost:8282",
"ui.example.com": "localhost:8283",
"api.example.com": "localhost:8284",
- }
- mux.Handle("/", NewRouter(routes))
+ }))
- bindAddress := env.Fetch("BIND_ADDR", ":8080")
- log.Fatal((&http.Server{
- Addr: bindAddress,
- Handler: mux,
- ReadHeaderTimeout: 10 * time.Second,
- ReadTimeout: 30 * time.Second,
- WriteTimeout: 2 * time.Minute,
- IdleTimeout: 5 * time.Minute,
- ErrorLog: log.Default(),
- }).ListenAndServe())
+ log.Fatal(srv.Run(srv.NewConfig(
+ env.Fetch("BIND_ADDR", ":8080"),
+ srv.WithMux(mux),
+ )))
}
pkg/srv/config.go
@@ -0,0 +1,42 @@
+package srv
+
+import (
+ "crypto/tls"
+ "net/http"
+)
+
+type Option func(*Config)
+
+type Config struct {
+ BindAddress string
+ Mux http.Handler
+ TLS *tls.Config
+}
+
+func WithMux(mux http.Handler) Option {
+ return func(config *Config) {
+ config.Mux = mux
+ }
+}
+
+func NewConfig(addr string, options ...Option) *Config {
+ if addr == "" {
+ addr = ":0"
+ }
+
+ c := &Config{
+ BindAddress: addr,
+ Mux: http.DefaultServeMux,
+ }
+ for _, option := range options {
+ option(c)
+ }
+ return c
+}
+
+func (c *Config) Run(server *http.Server) error {
+ if c.TLS != nil {
+ return server.ListenAndServeTLS("", "")
+ }
+ return server.ListenAndServe()
+}
pkg/srv/srv.go
@@ -0,0 +1,24 @@
+package srv
+
+import (
+ "log"
+ "net/http"
+ "time"
+)
+
+func New(cfg *Config) *http.Server {
+ return &http.Server{
+ Addr: cfg.BindAddress,
+ Handler: cfg.Mux,
+ TLSConfig: cfg.TLS,
+ ReadHeaderTimeout: 10 * time.Second,
+ ReadTimeout: 30 * time.Second,
+ WriteTimeout: 2 * time.Minute,
+ IdleTimeout: 5 * time.Minute,
+ ErrorLog: log.Default(),
+ }
+}
+
+func Run(c *Config) error {
+ return c.Run(New(c))
+}