Middleware
FnComponents are rendered by directing http requests through a special middleware function.
func MiddleWareFn(http.HandlerFunc, fncmp.HandleFn) http.HandlerFunc
It's a bit of a mouth full, so let's break it down.
http.HandlerFunc
This is the standard http.HandlerFunc that you would use in a normal http server. This is the HandlerFunc that we'll use to serve the index file.
- html
- templ
func HandleIndex(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/index.html")
}
func HandleIndex(w http.ResponseWriter, r *http.Request) {
c := Index()
c.Render(r.Context(), w)
}
fncmp.HandleFn
This is the function that will be used to handle the FnComponents within the scope of the route. If you read the introduction, you'll remember that we created a button component.
HandleMainFn receives context containing the http request, as well as information that fncmp communicates with fncmp.min.js to render the button component. fncmp.NewFn takes this context as well as the button component and returns a FnComponent.
func HandleMainFn(ctx context.Context) fncmp.FnComponent {
return fncmp.NewFn(ctx, button)
}
See the examples for tips on serving various templates and their components using fncmp.HandleFn