构建现代化Web应用:从中间件到前端框架
1. 中间件的应用
1.1 CORS中间件
在开发Web应用时,跨域资源共享(CORS)是一个重要的问题。我们使用自定义的中间件来包装Gorilla Mux CORS中间件,这样可以更方便地设置CORS白名单域名以及这些域名支持的HTTP方法。
1.2 JSON中间件
JSON(JavaScript Object Notation)是一种用于表示键值对和数组的数据格式。JSON中间件通过检查HTTP请求头来确保请求的数据是JSON格式。以下是JSON中间件的代码示例:
func JSONMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(wr http.ResponseWriter, req *http.Request) {
contentType := req.Header.Get("Content-Type")
if strings.TrimSpace(contentType) == "" {
var parseError error
contentType, _, parseError = mime.ParseMediaType(contentType)
if parseError != nil {
JSONError(wr, http.StatusBadRequest, "Bad or no c
超级会员免费看
订阅专栏 解锁全文
1391

被折叠的 条评论
为什么被折叠?



