Guides
Guides

XSRF Protection

Golf comes with built-in XSRF protection. To enable XSRF protection in your site, set xsrf_cookies in your app configuration to true.

package main

import (
	"github.com/dinever/golf"
)

func mainHandler(ctx *golf.Context) {
	ctx.Send("Hello World!")
}

func loginHandler(ctx *golf.Context) {
	ctx.Loader("default").Render("login.html", make(map[string]interface{}))
}

func loginHandlerPost(ctx *golf.Context) {
	ctx.Send("Hi, " + ctx.Request.FormValue("name"))
}

func main() {
	app := golf.New()
	app.Use(golf.XSRFProtectionMiddleware)
	app.View.SetTemplateLoader("default", ".")

	app.Get("/", mainHandler)
	app.Post("/login", loginHandlerPost)
	app.Get("/login", loginHandler)

	app.Run(":9000")
}
<html>
  <body>
    <form action="/login" method="post">
      Name:
      <input type="text" name="name">
      <input type="text" name="xsrf_token" value="{{ .xsrf_token }}">
      <input type="submit" value="Sign in">
    </form>
  </body>
</html>

When xsrf_cookies is set. Golf will set the _xsrf cookie for all users and block all POST, PUT and DELETE requests if the _xsrf value is not correct.

Make sure you included the field xsrf_token in every form submission when XSRF protection is enabled:

<input type="hidden" name="xsrf_token" value="{{ .xsrf_token }}">