Skip to content

Instantly share code, notes, and snippets.

@tkc
Created April 13, 2020 10:09
Show Gist options
  • Save tkc/aec1774885a32845b53b9c954ebcb78d to your computer and use it in GitHub Desktop.
Save tkc/aec1774885a32845b53b9c954ebcb78d to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"log"
"net/http"
"time"
jwtmiddleware "github.com/auth0/go-jwt-middleware"
jwt "github.com/dgrijalva/jwt-go"
"github.com/gorilla/mux"
)
type post struct {
Title string `json:"title"`
}
var public = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
post := &post{
Title: "public",
}
json.NewEncoder(w).Encode(post)
})
var private = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
post := &post{
Title: "private",
}
json.NewEncoder(w).Encode(post)
})
const SIGNINGKEY = "SIGNINGKEY...."
var GetTokenHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["admin"] = true
claims["sub"] = "54546557354"
claims["name"] = "taro"
claims["iat"] = time.Now()
claims["exp"] = time.Now().Add(time.Hour * 24).Unix()
tokenString, _ := token.SignedString([]byte(SIGNINGKEY))
w.Write([]byte(tokenString))
})
var JwtMiddleware = jwtmiddleware.New(
jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte(SIGNINGKEY), nil
},
SigningMethod: jwt.SigningMethodHS256,
},
)
func main() {
r := mux.NewRouter()
r.Handle("/public", public)
r.Handle("/private", JwtMiddleware.Handler(private))
r.Handle("/auth", GetTokenHandler)
if err := http.ListenAndServe(":8080", r); err != nil {
log.Fatal("ListenAndServe:", nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment