Skip to content

Commit

Permalink
Merge pull request #59 from uknth/tr-http-opts
Browse files Browse the repository at this point in the history
Allow flexible http multiplexer
  • Loading branch information
arpangupta committed Jun 21, 2023
2 parents d02832e + a3b5225 commit 01d1272
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
25 changes: 25 additions & 0 deletions kit/transport/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package http
import (
net_http "net/http"

tmux "github.com/dimfeld/httptreemux/v5"
"github.com/go-kit/kit/metrics"
)

Expand All @@ -15,6 +16,30 @@ type Mux interface {
Handler(method, url string, fn net_http.Handler)
}

type MuxOption func(*muxer)


type muxer struct {
*tmux.ContextMux
}

func NewDefaultMux(opts ...MuxOption) (Mux) {
mx := &muxer{tmux.NewContextMux()}

for _, o := range opts {
o(mx)
}

return mx
}

func WithDefaultMuxNoTrailingRedirect() MuxOption {
return func(mx *muxer) {
mx.RedirectTrailingSlash = false
}
}


// Metricser is wrapper for supported metrics agents
type Metricser interface {
Counter(prefix, name string) metrics.Counter
Expand Down
14 changes: 12 additions & 2 deletions kit/transport/http/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
net_http "net/http"
"time"

tmux "github.com/dimfeld/httptreemux/v5"
"github.com/unbxd/go-base/utils/log"
)

Expand All @@ -22,10 +21,13 @@ type (
// default HandlerOption
options []HandlerOption

muxOptions []MuxOption

//server level filter, applicable for all handlers
filters []Filter

mux Mux

logger log.Logger
monitors []string
metricer Metricser
Expand Down Expand Up @@ -290,15 +292,23 @@ func NewTransport(
options: []HandlerOption{
NewPopulateRequestContextRequestFunc(),
},
mux: tmux.NewContextMux(),
mux: nil,
muxOptions: make([]MuxOption, 0),
monitors: []string{"/ping"},
}



for _, o := range options {
o(transport)
}

if transport.mux == nil {
transport.mux = NewDefaultMux(transport.muxOptions...)
}

transport.Handler = transport.mux

if transport.filters != nil {
transport.Handler = Chain(transport.mux, transport.filters...)
}
Expand Down
7 changes: 7 additions & 0 deletions kit/transport/http/transport_opt.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,10 @@ func WithMonitors(monitors []string) TransportOption {
tr.monitors = append(tr.monitors, monitors...)
}
}

// WithMuxOption allows additional customisations of Multiplexer
func WithMuxOption(opt MuxOption) TransportOption {
return func(tr *Transport) {
tr.muxOptions = append(tr.muxOptions, opt)
}
}

0 comments on commit 01d1272

Please sign in to comment.