cardinalby / hureg

Huma registration extensions
MIT License
15 stars 0 forks source link

Is it possible to "Bring your own Router"? #1

Open polds opened 6 days ago

polds commented 6 days ago

More of a question than anything. I'd like to utilize some chi middleware, but it seems like middleware need to be initialized before a Huma instance is created. But basically I'm wondering if something like this is possible with Hureg:

    mux.Group(func(r chi.Router) {
        r.Use(middleware.Logger)

        api = api.
            AddBasePath("/health").
            AddOpHandler(op.AddTags("health-checking", "system"))

        // GET /health - Check the health of the service.
        hureg.Register(api, checkHealth, h.CheckHealth)
    })

At the moment it doesn't seem like Chi is able to get in front of anything.

cardinalby commented 6 days ago

Hi! That's a good question :)

  1. The Huma's idiomatic way would be rewrite the middleware to Huma format so that it can be used for specific operations (or groups with Hureg) since router-specific middlewares can only stay before Huma. If you want to use only this particular middleware, maybe it's the easiest way.

  2. Another way is try to implement "chi middleware" -> "huma middleware" mapper (kind of opposite to what is done in humachi adapter). You will need to reconstruct http.Request and writter (they are hidden in the private fields chiContext in humachi package). Looks a bit clumsy, not sure all the data can be extracted from huma.Context using the public methods.

  3. Hureg way. By your request I added a new APIGen.ReplaceHumaAPI method, so you can do the trick with a Huma instance defined for a particular Hureg group

P.S. Use Hureg v1.0.2 and put /health in place of /dog in my example :)