diff --git a/README.md b/README.md index 6ffc7e9..6c9c2d3 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ It is strongly recommended to generate the random key with the following functio Save the key in a file using `hex.EncodeToString()` and restrict access to that file. ``` Go -var key []byte = securecookie.GenerateRandomKey() +var key []byte = securecookie.MustGenerateRandomKey() ``` To mitigate the risk of an attacker getting the saved key, you might store a second @@ -67,7 +67,8 @@ difficult. ### Instantiating a cookie object -To return an error if an argument is invalid, use `securecookie.New()`. +A secure cookie is instantiated with the `New` function. It returns an error if an +argument is invalid. ``` Go obj, err := securecookie.New("session", key, securecookie.Params{ diff --git a/go.mod b/go.mod index c428f26..5482045 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module github.com/chmike/securecookie require github.com/gorilla/securecookie v1.1.1 + +go 1.13 diff --git a/securecookie.go b/securecookie.go index 1114769..1017ae3 100644 --- a/securecookie.go +++ b/securecookie.go @@ -104,6 +104,16 @@ func GenerateRandomKey() ([]byte, error) { return key, nil } +// MustGenerateRandomKey returns a random key of KeyLen bytes. +// It calls GenerateRandomKey and panics if it returns an error. +func MustGenerateRandomKey() []byte { + key, err := GenerateRandomKey() + if err != nil { + panic("securecookie: generate random key: " + err.Error()) + } + return key +} + // Params holds the optional cookie parameters. type Params struct { Path string // Optional : URL path to which the cookie will be returned diff --git a/securecookie_test.go b/securecookie_test.go index 8339ddc..c6a5b90 100644 --- a/securecookie_test.go +++ b/securecookie_test.go @@ -27,6 +27,21 @@ func TestGenerateKeyErrors(t *testing.T) { } } +func TestMustGenerateRandomKey(t *testing.T) { + key := MustGenerateRandomKey() + if len(key) != KeyLen { + t.Errorf("len of key is %d, expected %d", len(key), KeyLen) + } + forceError = 1 + defer func() { forceError = 0 }() + defer func() { + if r := recover(); r == nil { + t.Errorf("expected panic") + } + }() + MustGenerateRandomKey() +} + func TestCheckName(t *testing.T) { if err := checkName("toto"); err != nil { t.Errorf("unexpected error: %s", err)