Mixed named and unnamed function parameters

Issue

I have this function for authenticating JWT tokens (not middleware), which says:

package main

import (
"net/http"
"log"
"fmt"
"github.com/dgrijalva/jwt-go"
)

func ValidateToken(w http.ResponseWriter, r *http.Request) *jwt.Token {

//parse token
token, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, err error) {
    return VerifyKey, nil
})

//validate token
if err != nil {

    switch err.(type) {

    //something went wrong during validation
    case *jwt.ValidationError:
        vErr := err.(*jwt.ValidationError)

        switch vErr.Errors {

        case jwt.ValidationErrorExpired:
            w.WriteHeader(http.StatusUnauthorized)
            fmt.Fprintln(w, "Token expired")
            return nil

        default:
            w.WriteHeader(http.StatusInternalServerError)
            fmt.Fprintln(w, "Error parsing token")
            log.Printf("Validation error: %v\n", err)
            return nil
        }


    //something else went wrong
    default:
        w.WriteHeader(http.StatusInternalServerError)
        fmt.Fprintln(w, "Error parsing token")
        log.Printf("Validation error: %v\n", err)
        return nil
    }

}

return token

}

Then, in my handlers, I call this function to get the token and check if it is valid using the Valid property in the JWT Token struct. However, when I run the web server, I get an error on line 13, saying:

Mixed named and unnamed function parameters

Line 13 is the jwt.ParseFromRequest() call. Any thoughts on what I am doing wrong? I am new to Go.

Solution

You are defining a function inline (of type jwt.Keyfunc), but not binding it to anything. If VerifyKey is of type jwt.Keyfunc, then you can just change line 13 to

token, err := jwt.ParseFromRequest(r, VerifyKey)

Answered By – matt.s

Answer Checked By – Cary Denson (GoLangFix Admin)

Leave a Reply

Your email address will not be published.