#Add htmx to a go backend using Json REST

10 messages · Page 1 of 1 (latest)

misty bronze
#

My problem is that I don't want to create a mess in my backend.
Here's how the http handler looks right now.

func (h logisticsHandler) getItem(w http.ResponseWriter, r *http.Request) {
    id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
    if err != nil {
        return
    }

    item, _ := h.service.GetItem(r.Context(), id)

    res := newItemReponse(item)
    render.JSON(w, r, res)
}
```It only supports Json, but now HTMX would require me to also return html. I guess I could create a new handler that handles the requests on a different route, but then I have to do all the extraction and user auth twice. 

So then I had the idea to use `?type=json` param and return json by default... but I also don't like that.

Then I had the idea to switch based on the request headers, HTMX apparently sets `hx-header` to true. Maybe I switch and check if it exists and either return html or josn?

But it all feels like code clutter?
#

Thinking about it again, it's not even possible. If the user just visits the route ther won't be a hx header present.

#

So how am I supposed to manage all of this?

zinc summit
#

The best way to handle this is to allow the client to specify the content types its interested in

#

A client that wants json should ask for Accept: application/json or some other suitable mime type.

#

A browser or other client meant for humans will ask for Accept: text/html (among others)

#

This concept is usually referred to as "content negotiation" which you can learn more about here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation

MDN Web Docs

In HTTP, content negotiation is the mechanism that is used for serving different representations of a resource to the same URI to help the user agent specify which representation is best suited for the user (for example, which document language, which image format, or which content encoding).

misty bronze
#

It guess it would make sense if the endpoint would just return the actual html of an item and not the entire webpage

#

But I don't see how that would be possible.