middleware/find_token.go

45 lines
1.1 KiB
Go

package middleware
import (
"net/http"
"strings"
)
// TokenFromAuthorizationHeader tries to retrieve the token string from the
// "Authorization" request header and strips BEARER prefix if necessary
func TokenFromAuthorizationHeader(r *http.Request) string {
header := r.Header.Get("Authorization")
if len(header) > 7 && strings.ToUpper(header[0:6]) == "BEARER" {
return header[7:]
}
return header
}
// TokenFromHeader tries to retrieve the token string from the given header
func TokenFromHeader(headerKey string) func(r *http.Request) string {
return func(r *http.Request) string {
return r.Header.Get(headerKey)
}
}
// TokenFromQuery tries to retrieve the token string from the given query param
func TokenFromQuery(param string) func(r *http.Request) string {
return func(r *http.Request) string {
return r.URL.Query().Get(param)
}
}
// TokenFromCookie tries to retrieve the token string from a given cookie
func TokenFromCookie(cookieName string) func(r *http.Request) string {
return func(r *http.Request) string {
cookie, err := r.Cookie(cookieName)
if err != nil {
return ""
}
return cookie.Value
}
}