`HttpHandlerFunc 简写 —— func(http.ResponseWriter, *http.Request)` 是否有必要?

如题,这一节在 app/http/middlewares/middleware.go 中对HttpHandlerFunc 做了一个 type 封装。

package middlewares

import "net/http"

// HttpHandlerFunc 简写 —— func(http.ResponseWriter, *http.Request)
type HttpHandlerFunc func(http.ResponseWriter, *http.Request)

实际 net/http 包本身是有 HandlerFunc 这个 type 的,直接使用是不是比较省事。

package middlewares

import (
    "goblog/pkg/auth"
    "goblog/pkg/flash"
    "net/http"
)

// Auth 登录用户才可以访问
func Auth(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        if !auth.Check() {
            flash.Warning("登录用户才能访问此页面")
            http.Redirect(w, r, "/", http.StatusFound)
            return
        }

        next(w, r)
    }
}
黑哈尔
讨论数量: 4

是的,有道理

2年前 评论

你说的对, 我看到这里的时候也觉得奇怪

2年前 评论

区别:

  • 自定义封装的 HttpHandlerFunc 只是一个普通函数 func(http.ResponseWriter, *http.Request) 类型
  • http.HandlerFunc 实现了 http.ServeHTTP 的类型
7个月前 评论
RunningHuang 5个月前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!