Last active
September 5, 2020 19:36
-
-
Save empijei/2950085e18884209211aeaf3a46a3da0 to your computer and use it in GitHub Desktop.
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 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