Skip to content

Instantly share code, notes, and snippets.

@empijei
Last active September 5, 2020 19:36
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save empijei/2950085e18884209211aeaf3a46a3da0 to your computer and use it in GitHub Desktop.
Save empijei/2950085e18884209211aeaf3a46a3da0 to your computer and use it in GitHub Desktop.
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