net/http golang 中的链接中间件

Chaining middleware in net/http golang

我正在尝试向授权中间件添加上下文。 ContextHandler 是一个处理程序,它将传递给 api 处理程序以处理连接和配置变量。结构方法 ServeHTTP 也已添加到 ContextHandler 中,以便它满足 net/Http 正确处理请求的接口。

CheckAuth 是接受检查令牌验证等请求的中间件,如果令牌有效,则执行 ServeHTTP 方法,如果无效,Returns 响应中的适当错误。

代码可以编译,但我在 ServeHTTP 方法中遇到错误。

type ContextHandler struct {
    *AppContext
     Handler func(*AppContext, http.ResponseWriter, *http.Request)(int, error)

}

type AppContext struct {
   Db    *mgo.Session
   Config *simplejson.Json
}


func (ah *ContextedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

status, err := ah.handler(ah.AppContext, w, r)
if err != nil {
     switch status {
    case http.StatusNotFound:
        http.NotFound(w, r)
      case http.StatusInternalServerError:
          http.Error(w, http.StatusText(status), status)
    default:
        http.Error(w, http.StatusText(405), 405)
    }}}





func CheckAuth(h http.Handler) http.Handler {
    log.Println("Entered in CheckAuth")
    f := func( w http.ResponseWriter, r *http.Request) {
    authorizationToken := r.Header.Get("Authorization")
    if authorizationToken != ""{
        secret := []byte("somejunk")
        var credentials authorization
        token, err := jwt.ParseWithClaims(authorizationToken, &credentials, func(t *jwt.Token) (interface{}, error) {
        return []byte(secret), nil
        })

        if err == nil && token.Valid {
            //If everything is fine serve the Http request
            h.ServeHTTP( w, r)
            return 

            } else {
                  //Some response returned
                  json.NewEncoder(w).Encode(response)
                  return 
                  }
        //Check if user exists in the database 
        if dberr != nil {
           //SOmeresponse to be returned
          json.NewEncoder(w).Encode(response)
          return 
        }
      }else{
          response := simplejson.New()
          //response authorization header is missing
          json.NewEncoder(w).Encode(response)
          return 

        }
}
        return http.HandlerFunc(f)

}

func Initdb(configfile  *simplejson.Json) *mgo.Session {
   //return mongodbsession, copy and close while using it
}

In main.go file in the parent package 
func main() {
      var FileUploadContextHandler *ContextedHandler = &ContextedHandler{&context, filesystem.FileUpload}
     router.Methods("POST").Path("/decentralizefilesystem/fileupload").Name("FileUpload").Handler(CheckAuth(FileUploadContextHandler))
  }

I am getting this error
    2018/07/08 20:45:38 http: panic serving 127.0.0.1:52732: runtime error: invalid memory address or nil pointer dereference
goroutine 35 [running]:
net/http.(*conn).serve.func1(0xc4202ce140)
    /usr/local/go/src/net/http/server.go:1726 +0xd0
panic(0x6fe680, 0x92cb10)
    /usr/local/go/src/runtime/panic.go:502 +0x229
gitlab.com/mesha/Gofeynmen/vendor/gopkg.in/mgo%2ev2.(*Session).Copy(0x0, 0x7ff9485fb060)
    /home/feynman/goworkspace/src/gitlab.com/mesha/Gofeynmen/vendor/gopkg.in/mgo.v2/session.go:1589 +0x22
gitlab.com/mesha/Gofeynmen/appsettings.CheckAuth.func1(0x7ff9485fb060, 0xc420276300, 0xc4202e4200)
    /home/feynman/goworkspace/src/gitlab.com/mesha/Gofeynmen/appsettings/appsettings.go:115 +0x361
net/http.HandlerFunc.ServeHTTP(0xc420290180, 0x7ff9485fb060, 0xc420276300, 0xc4202e4200)
    /usr/local/go/src/net/http/server.go:1947 +0x44
github.com/gorilla/mux.(*Router).ServeHTTP(0xc42024a310, 0x7ff9485fb060, 0xc420276300, 0xc4202e4200)
    /home/feynman/goworkspace/src/github.com/gorilla/mux/mux.go:162 +0xed
github.com/gorilla/handlers.loggingHandler.ServeHTTP(0x7a8120, 0xc42000e018, 0x7a7b20, 0xc42024a310, 0x7aad60, 0xc4202f0000, 0xc4202e4000)
    /home/feynman/goworkspace/src/github.com/gorilla/handlers/handlers.go:69 +0x123
github.com/gorilla/handlers.(*cors).ServeHTTP(0xc4202c4090, 0x7aad60, 0xc4202f0000, 0xc4202e4000)
    /home/feynman/goworkspace/src/github.com/gorilla/handlers/cors.go:52 +0xa3b
net/http.serverHandler.ServeHTTP(0xc4202da0d0, 0x7aad60, 0xc4202f0000, 0xc4202e4000)
    /usr/local/go/src/net/http/server.go:2694 +0xbc
net/http.(*conn).serve(0xc4202ce140, 0x7ab120, 0xc42025e100)
    /usr/local/go/src/net/http/server.go:1830 +0x651
created by net/http.(*Server).Serve
    /usr/local/go/src/net/http/server.go:2795 +0x27b

ah 不是指向 ContextedHandler.

的指针时,这可能是试图从 (ah *ContextedHandler) 中取消引用 ah

此作业中的类型不匹配:

var FileUploadContextHandler *ContextedHandler =
    ContextedHandler{&context, filesystem.FileUpload}

在左侧输入 *ContextedHandler。在右侧,您输入 ContextedHandler.

你是说

var FileUploadContextHandler *ContextedHandler =
    &ContextedHandler{&context, filesystem.FileUpload} 

或者你的意思是

var FileUploadContextHandler ContextedHandler =
    ContextedHandler{&context, filesystem.FileUpload}

?


传递给 CheckAuth 函数的参数似乎也不匹配函数签名:

CheckAuth(FileUploadContextHandler)

FileUploadContextHandler 是类型 *ContextedHandler。函数签名是:

func CheckAuth(h contextHandlerFunc) contextHandlerFunc

contextHandlerFunc 的类型定义似乎不是您共享的代码的一部分。


此行有问题:

router.Methods("POST").Path("/decentralizefilesystem/fileupload").Name("FileUpload").Handler(CheckAuth(FileUploadContextHandler))

...如果将其分解为多行的变量赋值,然后找出恐慌指向哪一行,将更容易追踪。