CSRF(Cross-Site Request Forgery) attack protection

CSRF package for Golang, it provides CSRF(Cross-Site Request Forgery) attack protection.
Installation
go get github.com/clevergo/csrf
Usage
package main
import (
"github.com/clevergo/csrf"
"github.com/headwindfly/utils"
"fmt"
)
func main() {
maskLen := 8 // length of mark bytes.
tokenLen := 32 // length of true token bytes.
// True token bytes.
// Note that the true token must not be exposed.
// You can store it in session or something else, it is up to your application.
// What's more, you just need create unique token for per session once.
token := utils.RandomBytes(tokenLen) // You can generate bytes by other way, it is up to you.
// Generate encoded token.
// The encoded token should exposed to client.
encodedToken := csrf.Generate(maskLen, token)
// Validate the token.
// encodedToken can be catched from request,
// that is to say, sensitive request(such as POST request) should carry the encoded token.
err := csrf.Validate(maskLen, []byte(encodedToken), token)
if err != nil {
// Handle error
panic(err.Error())
}
fmt.Println("Congratulations! Encoded token is valid.")
// Validate invalid token
err = csrf.Validate(maskLen, []byte(encodedToken), []byte("Invalid token."))
if err == nil {
panic("Something wrong.")
}
}
You can run the following command to check result.
go run $GOPATH/src/github.com/clevergo/csrf/examples/main.go
See also Example.