go-paste/svc.http.go

50 lines
1004 B
Go
Raw Normal View History

2023-10-19 17:05:41 -06:00
package main
import (
"context"
"log"
"net/http"
"strings"
"github.com/rs/cors"
"go.sour.is/pkg/env"
"go.sour.is/pkg/lg"
"go.sour.is/pkg/mux"
"go.sour.is/pkg/service"
"go.sour.is/pkg/slice"
)
var _ = apps.Register(20, func(ctx context.Context, svc *service.Harness) error {
s := &http.Server{}
svc.Add(s)
mux := mux.New()
2023-11-08 13:44:28 -07:00
s.Handler = cors.AllowAll().Handler(mux)
hdlr := s.Handler
2023-10-19 17:05:41 -06:00
s.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(r.Method, r.URL.Path)
2023-11-08 13:44:28 -07:00
hdlr.ServeHTTP(w, r)
2023-10-19 17:05:41 -06:00
})
s.Addr = env.Default("HTTP_LISTEN", ":8080")
if strings.HasPrefix(s.Addr, ":") {
s.Addr = "[::]" + s.Addr
}
svc.OnStart(func(ctx context.Context) error {
_, span := lg.Span(ctx)
defer span.End()
log.Print("Listen on ", s.Addr)
span.AddEvent("begin listen and serve on " + s.Addr)
mux.Add(slice.FilterType[interface{ RegisterHTTP(*http.ServeMux) }](svc.Services...)...)
return s.ListenAndServe()
})
svc.OnStop(s.Shutdown)
return nil
})