summaryrefslogtreecommitdiff
path: root/pkg
diff options
context:
space:
mode:
authormo khan <mo@mokhan.ca>2025-03-13 09:12:17 -0600
committermo khan <mo@mokhan.ca>2025-03-13 09:12:17 -0600
commit6ad85c4bd167c9f114c1d2574f4887826689b76d (patch)
treeb45f77c71163b7a637ce3d4a5db87f46e67a7659 /pkg
parent0c50b105de6c0fc0c5a941af0adf59a40124ecb1 (diff)
refactor: extract srv package
Diffstat (limited to 'pkg')
-rw-r--r--pkg/srv/config.go42
-rw-r--r--pkg/srv/srv.go24
2 files changed, 66 insertions, 0 deletions
diff --git a/pkg/srv/config.go b/pkg/srv/config.go
new file mode 100644
index 0000000..c02a9c7
--- /dev/null
+++ b/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()
+}
diff --git a/pkg/srv/srv.go b/pkg/srv/srv.go
new file mode 100644
index 0000000..a2be363
--- /dev/null
+++ b/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))
+}