Groups
Uber-FX
group is a feature that allows you to consume and produce
multiple values of the same type. This makes it easier to influence/configure different instances.
Mortar has different groups, but we will focus on one of them here.
// InternalHTTPHandlers - Internal Http Handlers group. Mortar comes with several internal handlers, you can add yours.
InternalHTTPHandlers = partial.FxGroupInternalHTTPHandlers
//InternalHTTPHandlerFunctions - Internal Http Handler Functions group. Similar toInternalHttpHandlers but for functions
InternalHTTPHandlerFunctions = partial.FxGroupInternalHTTPHandlerFunctions
Build Information
Similar to everything else in Uber-FX
, to register a new instance into a fx.Group
you need to create a Constructor.
We will look at one of the internal handlers: Build Information.
In this example we want to register a new internal ["/<path>/<pattern>"
-> http.HandlerFunc
] pair.
-
Let’s start by defining a constructor that will return
http.HandlerFunc
:func (s *selfHandlerDeps) BuildInfo() http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { information := mortar.GetBuildInformation(true) // using true here will insert a default value if there is none if err := json.NewEncoder(w).Encode(information); err != nil { w.WriteHeader(http.StatusInternalServerError) s.Logger.WithError(err).Warn(nil, "failed to serve build info") } } }
-
Create an
HTTPHandlerPatternPair
. This is the part where you define on what path this handler will be served:// SelfHandlers this service information handlers func SelfHandlers(deps selfHandlerDeps) []partial.HTTPHandlerPatternPair { return []partial.HTTPHandlerPatternPair{ {Pattern: "/self/build", Handler: deps.BuildInfo()}, ... } }
-
Tell
Uber-FX
that we want this instance ofHTTPHandlerPatternPair
added to thegroups.InternalHTTPHandlerFunctions
group.func InternalSelfHandlersFxOption() fx.Option { return fx.Provide( fx.Annotated{ Group: groups.InternalHTTPHandlers + ",flatten", Target: handlers.SelfHandlers, }) }
-
Lastly, in your application you need to provide the above
InternalSelfHandlersFxOption()
option toUber-FX
graph, here you can see how it’s done in the demo.return fx.New( ... InternalSelfHandlersFxOption(), ... )