Skip to content

Instantly share code, notes, and snippets.

@bryanjeal
Created April 9, 2015 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryanjeal/448cc89b30643f610315 to your computer and use it in GitHub Desktop.
Save bryanjeal/448cc89b30643f610315 to your computer and use it in GitHub Desktop.
nosurf simple.go example with enctype="multipart/form-data"
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