gogo-gormgo-chi

Gorm and go-chi REST patch resource


I am building a REST API using chi and gorm

I want to have a patch route where I can update only the properties I receive in the request body.

I am not sure how is the best way of passing there properties to gorm update method.

Which would be a good way of doing so?

Here is the handler method.

func (m Env) UpdateHandler(w http.ResponseWriter, r *http.Request) {
    var delta InsurancePolicy
    insurancePolicy := r.Context().Value("insurancePolicy").(InsurancePolicy)

    err := json.NewDecoder(r.Body).Decode(&delta)
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        return
    }


    result := m.DB.Model(&insurancePolicy).Update(delta)

    if result.Error != nil {
        w.WriteHeader(http.StatusInternalServerError)
    } else {
        err := json.NewEncoder(w).Encode(insurancePolicy)
        if err != nil {
            w.WriteHeader(http.StatusInternalServerError)
        }
    }

}

It uses this middleware to preload the request:

func (m Env) InsurancePolicyCtx(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        var insurancePolicy InsurancePolicy
        result := m.DB.First(&insurancePolicy, chi.URLParam(r, "id"))

        if result.Error != nil {
            w.WriteHeader(http.StatusNotFound)
            return
        }

        ctx := context.WithValue(r.Context(), "insurancePolicy", insurancePolicy)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

Solution

  • The right Gorm method to use for updating non zero values is Updates