From 12df459840d3ed037bd00421827a9e54e3121ed6 Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Sun, 27 May 2018 07:59:25 +0000 Subject: [PATCH] mhttp: initial implementation, very basic --- mhttp/mhttp.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 mhttp/mhttp.go diff --git a/mhttp/mhttp.go b/mhttp/mhttp.go new file mode 100644 index 0000000..8cf530c --- /dev/null +++ b/mhttp/mhttp.go @@ -0,0 +1,36 @@ +// Package mhttp extends the standard package with extra functionality which is +// commonly useful +package mhttp + +import ( + "context" + "net/http" + + "github.com/mediocregopher/mediocre-go-lib/mcfg" + "github.com/mediocregopher/mediocre-go-lib/mlog" +) + +// CfgServer initializes and returns an *http.Server which will initialize on +// the Start hook. This also sets up config params for configuring the address +// being listened on. +func CfgServer(cfg *mcfg.Cfg, h http.Handler) *http.Server { + cfg = cfg.Child("http") + addr := cfg.ParamString("addr", ":0", "Address to listen on. Default is any open port") + + srv := http.Server{Handler: h} + cfg.Start.Then(func(ctx context.Context) error { + srv.Addr = *addr + kv := mlog.KV{"addr": *addr} + mlog.Info("HTTP server listening", kv) + go func() { + err := srv.ListenAndServe() + // TODO the listening log should happen here, somehow, now that we + // know the actual address being listened on + mlog.Fatal("http server fataled", kv, mlog.ErrKV(err)) + }() + return nil + }) + + // TODO shutdown logic + return &srv +}