Skip to content

Commit

Permalink
refactor: add service.SimpleHTTP to reduce required boilerplate
Browse files Browse the repository at this point in the history
  • Loading branch information
ThinkChaos committed Aug 30, 2024
1 parent 4660c5c commit 47f8e4e
Show file tree
Hide file tree
Showing 9 changed files with 54 additions and 83 deletions.
16 changes: 2 additions & 14 deletions api/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@ import (
"github.com/0xERR0R/blocky/config"
"github.com/0xERR0R/blocky/service"
"github.com/0xERR0R/blocky/util"
"github.com/go-chi/chi/v5"
)

// Service implements service.HTTPService.
type Service struct {
service.HTTPInfo
service.SimpleHTTP
}

func NewService(cfg config.APIService, server StrictServerInterface) *Service {
Expand All @@ -19,21 +18,10 @@ func NewService(cfg config.APIService, server StrictServerInterface) *Service {
)

s := &Service{
HTTPInfo: service.HTTPInfo{
Info: service.Info{
Name: "API",
Endpoints: endpoints,
},

Mux: chi.NewMux(),
},
SimpleHTTP: service.NewSimpleHTTP("API", endpoints),
}

registerOpenAPIEndpoints(s.Mux, server)

return s
}

func (s *Service) Merge(other service.Service) (service.Merger, error) {
return service.MergeHTTP(s, other)
}
16 changes: 2 additions & 14 deletions metrics/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@ import (
"github.com/0xERR0R/blocky/config"
"github.com/0xERR0R/blocky/service"
"github.com/0xERR0R/blocky/util"
"github.com/go-chi/chi/v5"
"github.com/prometheus/client_golang/prometheus/promhttp"
)

// Service implements service.HTTPService.
type Service struct {
service.HTTPInfo
service.SimpleHTTP
}

func NewService(cfg config.MetricsService, metricsCfg config.Metrics) *Service {
Expand All @@ -25,14 +24,7 @@ func NewService(cfg config.MetricsService, metricsCfg config.Metrics) *Service {
}

s := &Service{
HTTPInfo: service.HTTPInfo{
Info: service.Info{
Name: "Metrics",
Endpoints: endpoints,
},

Mux: chi.NewMux(),
},
SimpleHTTP: service.NewSimpleHTTP("Metrics", endpoints),
}

s.Mux.Handle(
Expand All @@ -42,7 +34,3 @@ func NewService(cfg config.MetricsService, metricsCfg config.Metrics) *Service {

return s
}

func (s *Service) Merge(other service.Service) (service.Merger, error) {
return service.MergeHTTP(s, other)
}
15 changes: 2 additions & 13 deletions server/doh.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
)

type dohService struct {
service.HTTPInfo
service.SimpleHTTP

handler dnsHandler
}
Expand All @@ -25,14 +25,7 @@ func newDoHService(cfg config.DoHService, handler dnsHandler) *dohService {
)

s := &dohService{
HTTPInfo: service.HTTPInfo{
Info: service.Info{
Name: "DoH",
Endpoints: endpoints,
},

Mux: chi.NewMux(),
},
SimpleHTTP: service.NewSimpleHTTP("DoH", endpoints),

handler: handler,
}
Expand All @@ -50,10 +43,6 @@ func newDoHService(cfg config.DoHService, handler dnsHandler) *dohService {
return s
}

func (s *dohService) Merge(other service.Service) (service.Merger, error) {
return service.MergeHTTP(s, other)
}

func (s *dohService) handleGET(rw http.ResponseWriter, req *http.Request) {
dnsParam, ok := req.URL.Query()["dns"]
if !ok || len(dnsParam[0]) < 1 {
Expand Down
19 changes: 6 additions & 13 deletions server/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
// that expose everything. The goal is to split it up
// and remove it.
type httpMiscService struct {
service.HTTPInfo
service.SimpleHTTP
}

func newHTTPMiscService(cfg *config.Config) *httpMiscService {
Expand All @@ -28,20 +28,13 @@ func newHTTPMiscService(cfg *config.Config) *httpMiscService {
service.EndpointsFromAddrs(service.HTTPSProtocol, cfg.Ports.HTTPS),
)

return &httpMiscService{
HTTPInfo: service.HTTPInfo{
Info: service.Info{
Name: "HTTP",
Endpoints: endpoints,
},

Mux: createHTTPRouter(cfg),
},
s := &httpMiscService{
SimpleHTTP: service.NewSimpleHTTP("API", endpoints),
}
}

func (s *httpMiscService) Merge(other service.Service) (service.Merger, error) {
return service.MergeHTTP(s, other)
configureHTTPRouter(s.Router(), cfg)

return s
}

// httpServer implements subServer for HTTP.
Expand Down
14 changes: 5 additions & 9 deletions server/server_endpoints.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,37 +60,33 @@ func (s *Server) Query(
return s.resolve(ctx, req)
}

func createHTTPRouter(cfg *config.Config) *chi.Mux {
router := chi.NewRouter()

func configureHTTPRouter(router chi.Router, cfg *config.Config) {
configureDebugHandler(router)

configureDocsHandler(router)

configureStaticAssetsHandler(router)

configureRootHandler(cfg, router)

return router
}

func configureDocsHandler(router *chi.Mux) {
func configureDocsHandler(router chi.Router) {
router.Get("/docs/openapi.yaml", func(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set(contentTypeHeader, yamlContentType)
_, err := writer.Write([]byte(docs.OpenAPI))
logAndResponseWithError(err, "can't write OpenAPI definition file: ", writer)
})
}

func configureStaticAssetsHandler(router *chi.Mux) {
func configureStaticAssetsHandler(router chi.Router) {
assets, err := web.Assets()
util.FatalOnError("unable to load static asset files", err)

fs := http.FileServer(http.FS(assets))
router.Handle("/static/*", http.StripPrefix("/static/", fs))
}

func configureRootHandler(cfg *config.Config, router *chi.Mux) {
func configureRootHandler(cfg *config.Config, router chi.Router) {
router.Get("/", func(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set(contentTypeHeader, htmlContentType)

Expand Down Expand Up @@ -149,6 +145,6 @@ func logAndResponseWithError(err error, message string, writer http.ResponseWrit
}
}

func configureDebugHandler(router *chi.Mux) {
func configureDebugHandler(router chi.Router) {
router.Mount("/debug", middleware.Profiler())
}
21 changes: 21 additions & 0 deletions service/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,29 @@ type HTTPInfo struct {
Mux *chi.Mux
}

func NewHTTPInfo(name string, endpoints []Endpoint) HTTPInfo {
return HTTPInfo{
Info: NewInfo(name, endpoints),

Mux: chi.NewMux(),
}
}

func (i *HTTPInfo) Router() chi.Router { return i.Mux }

var _ HTTPService = (*SimpleHTTP)(nil)

// SimpleHTTP implements HTTPService usinig the default HTTP merger.
type SimpleHTTP struct{ HTTPInfo }

func NewSimpleHTTP(name string, endpoints []Endpoint) SimpleHTTP {
return SimpleHTTP{HTTPInfo: NewHTTPInfo(name, endpoints)}
}

func (s *SimpleHTTP) Merge(other Service) (Merger, error) {
return MergeHTTP(s, other)
}

// MergeHTTP merges two compatible HTTPServices.
//
// The second parameter is of type `Service` to make it easy to call
Expand Down
27 changes: 8 additions & 19 deletions service/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ var _ = Describe("Service HTTP", func() {
Describe("HTTPInfo", func() {
It("returns the expected router", func() {
endpoints := EndpointsFromAddrs("proto", []string{":1", "localhost:2"})
sut := HTTPInfo{Info{"name", endpoints}, chi.NewMux()}
sut := NewHTTPInfo("name", endpoints)

Expect(sut.ServiceName()).Should(Equal("name"))
Expect(sut.ExposeOn()).Should(Equal(endpoints))
Expand Down Expand Up @@ -70,17 +70,17 @@ var _ = Describe("Service HTTP", func() {
})

It("doesn't modify what HTTP routes match", func() {
apiSvc := newFakeHTTPService("API", ":443")
apiSvc := NewSimpleHTTP("API", EndpointsFromAddrs("https", []string{":443"}))
apiSvc.Router().Post("/api", nil)
apiSvc.Router().Get("/api/get/", nil)

dohSvc := newFakeHTTPService("DoH", ":443")
dohSvc := NewSimpleHTTP("DoH", EndpointsFromAddrs("https", []string{":443"}))
dohSvc.Router().Route("/dns-query", func(mux chi.Router) {
mux.Get("/", nil)
mux.Post("/", nil)
})

merged, err := apiSvc.Merge(dohSvc)
merged, err := apiSvc.Merge(&dohSvc)
Expect(err).Should(Succeed())

casted, ok := merged.(HTTPService)
Expand All @@ -105,20 +105,9 @@ var _ = Describe("Service HTTP", func() {
})
})

type fakeHTTPService struct {
HTTPInfo
}

func newFakeHTTPService(name string, addrs ...string) *fakeHTTPService {
mux := chi.NewMux()
mux.Get("/"+name, nil)

return &fakeHTTPService{HTTPInfo{
Info: Info{Name: name, Endpoints: EndpointsFromAddrs("http", addrs)},
Mux: mux,
}}
}
func newFakeHTTPService(name string, addrs ...string) HTTPService {
svc := NewSimpleHTTP(name, EndpointsFromAddrs("http", addrs))
svc.Router().Get("/"+name, nil)

func (s *fakeHTTPService) Merge(other Service) (Merger, error) {
return MergeHTTP(s, other)
return &svc
}
7 changes: 7 additions & 0 deletions service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ type Info struct {
Endpoints []Endpoint
}

func NewInfo(name string, endpoints []Endpoint) Info {
return Info{
Name: name,
Endpoints: endpoints,
}
}

func (i *Info) ServiceName() string { return i.Name }
func (i *Info) ExposeOn() []Endpoint { return i.Endpoints }
func (i *Info) String() string { return svcString(i) }
Expand Down
2 changes: 1 addition & 1 deletion service/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ var _ = Describe("Service", func() {

Describe("Info", func() {
endpoints := EndpointsFromAddrs("proto", []string{":1", "localhost:2"})
sut := Info{"name", endpoints}
sut := NewInfo("name", endpoints)

It("implements Service", func() {
var svc Service = &sut
Expand Down

0 comments on commit 47f8e4e

Please sign in to comment.