英文:
Gorm and go-chi REST patch resource
问题
我想要一个patch路由,可以只更新请求体中接收到的属性。
我不确定将这些属性传递给gorm的update方法的最佳方式是什么。
有什么好的方法可以实现这样的功能吗?
以下是处理程序方法的代码:
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)
}
}
}
它使用以下中间件预加载请求:
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))
})
}
英文:
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))
})
}
答案1
得分: 1
更新非零值的正确 Gorm 方法是 Updates
英文:
The right Gorm method to use for updating non zero values is Updates
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论