0

我正在尝试向授权中间件添加上下文。ContextHandler 是一个处理程序,它将被传递给 api 处理程序以处理连接和配置变量。ContextHandler 中还添加了一个 struct Method ServeHTTP,以便它满足 net/Http 接口以正确处理请求。

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

代码编译,但我在 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
4

1 回答 1

1

当不是指向 a 的指针时,它可能试图ah从.(ah *ContextedHandler)ahContextedHandler

此作业中的类型不匹配:

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

在左侧你有 type *ContextedHandler。在右侧你有 type 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))

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

于 2018-07-08T16:12:55.140 回答