Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package csrf
import "errors"
// This is just an example on how to reduce redundant code in Go
// Original file: https://github.com/gofiber/csrf/blob/dde96da6711a2cc01709a66730c2e16328b22047/main.go
// csrfFromExtractor returns a function can be used to bind to a parameter name to extract a csrf token from a Ctx.
func csrfFromExtractor(errMessage string, extractor func(c *fiber.Ctx, param string) string) func(string) func(c *fiber.Ctx) (string, error) {
return func(param string) func(c *fiber.Ctx) (string, error) {
return func(c *fiber.Ctx) (string, error) {
token := extractor(c, param)
if token == "" {
return "", errors.New("missing csrf token in " + errMessage)
}
return token, nil
}
}
}
var (
// csrfFromQuery returns a function that extracts token from the query string.
csrfFromQuery = csrfFromExtractor("query", (*fiber.Ctx).Query)
// csrfFromHeader returns a function that extracts token from the request header.
csrfFromHeader = csrfFromExtractor("header", (*fiber.Ctx).Get)
// csrfFromParam returns a function that extracts token from the url parameters.
csrfFromParam = csrfFromExtractor("url parameter", (*fiber.Ctx).Params)
// csrfFromParam returns a function that extracts token from the form values.
csrfFromForm = csrfFromExtractor("form parameter", (*fiber.Ctx).FormValue)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment