1 Star 0 Fork 0

Paulden/Microservices

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
middleware.go 1.08 KB
一键复制 编辑 原始数据 按行查看 历史
package handlers
import (
"context"
"fmt"
"gitee.com/guuzaa/microservices/product-api/data"
"net/http"
)
// MiddlewareValidateProduct validates the product in the request and calls next if ok
func (p Products) MiddlewareValidateProduct(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Add("Content-Type", "application/json")
prod := &data.Product{}
if err := data.FromJSON(prod, r.Body); err != nil {
p.l.Println("[ERROR] deserializing product", err)
http.Error(rw, "Error reading product", http.StatusBadRequest)
return
}
//validate the product
if err := p.v.Validate(prod); len(err) != 0 {
p.l.Println("[ERROR] validating product", err)
http.Error(
rw,
fmt.Sprintf("Error validating product: %s", err),
http.StatusBadRequest)
return
}
// add the product to the context
ctx := context.WithValue(r.Context(), KeyProduct{}, prod)
r = r.WithContext(ctx)
// Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(rw, r)
})
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/guuzaa/microservices.git
git@gitee.com:guuzaa/microservices.git
guuzaa
microservices
Microservices
9ba62408bc9f

搜索帮助