Skip to content

Commit

Permalink
Added Martini example
Browse files Browse the repository at this point in the history
  • Loading branch information
mgonto committed May 12, 2015
1 parent ad9d815 commit 41716e4
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
10 changes: 10 additions & 0 deletions examples/martini-example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Negroni example

This is an example of how to use the middleware with Martini.

# Using it

To try this out, first install all dependencies with `go install` and then run `go run main.go` to start the app.

* Call `http://localhost:3001/ping` to get a JSon response without the need of a JWT.
* Call `http://localhost:3001/secured/ping` with a JWT signed with `My Secret` to get a response back.
55 changes: 55 additions & 0 deletions examples/martini-example/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package main

import (
"encoding/json"
"github.com/auth0/go-jwt-middleware"
"github.com/go-martini/martini"
"github.com/dgrijalva/jwt-go"
"net/http"
)

func main() {

StartServer()

}

func StartServer() {
m := martini.Classic()

jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte("My Secret"), nil
},
});

m.Get("/ping", PingHandler);
m.Get("/secured/ping", jwtMiddleware.CheckJWT, SecuredPingHandler);

m.Run();
}

type Response struct {
Text string `json:"text"`
}

func respondJson(text string, w http.ResponseWriter) {
response := Response{text}

jsonResponse, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json")
w.Write(jsonResponse)
}

func PingHandler(w http.ResponseWriter, r *http.Request) {
respondJson("All good. You don't need to be authenticated to call this", w)
}

func SecuredPingHandler(w http.ResponseWriter, r *http.Request) {
respondJson("All good. You only get this message if you're authenticated", w)
}

0 comments on commit 41716e4

Please sign in to comment.