Created
April 9, 2015 21:10
-
-
Save bryanjeal/448cc89b30643f610315 to your computer and use it in GitHub Desktop.
nosurf simple.go example with enctype="multipart/form-data"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"html/template" | |
"net/http" | |
"github.com/justinas/nosurf" | |
) | |
var templateString = ` | |
<!doctype html> | |
<html> | |
<body> | |
{{ if .name }} | |
<p>Your name: {{ .name }}</p> | |
{{ end }} | |
<form action="/" method="post" enctype="multipart/form-data"> | |
<input type="text" name="name"> | |
<input type="hidden" name="csrf_token" value="{{ .token }}"> | |
<input type="submit" value="Send"> | |
</form> | |
</body> | |
</html> | |
` | |
var templ = template.Must(template.New("t1").Parse(templateString)) | |
func myFunc(w http.ResponseWriter, r *http.Request) { | |
context := make(map[string]string) | |
context["token"] = nosurf.Token(r) | |
if r.Method == "POST" { | |
context["name"] = r.FormValue("name") | |
} | |
templ.Execute(w, context) | |
} | |
func failHand(w http.ResponseWriter, r *http.Request) { | |
// will return the reason of the failure | |
fmt.Fprintf(w, "%s\n", nosurf.Reason(r)) | |
} | |
func main() { | |
http.HandleFunc("/", myFunc) | |
csrfHandler := nosurf.New(http.DefaultServeMux) | |
csrfHandler.SetFailureHandler(http.HandlerFunc(failHand)) | |
fmt.Println("Listening on http://127.0.0.1:8000/") | |
http.ListenAndServe(":8000", csrfHandler) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment