Commit 94ffbad

mo khan <mo@mokhan.ca>
2025-05-07 01:54:28
feat: add option to base64 encode a cookie value
1 parent f7ded7c
Changed files (2)
pkg/cookie/option.go
@@ -1,6 +1,7 @@
 package cookie
 
 import (
+	"encoding/base64"
 	"fmt"
 	"net/http"
 	"time"
@@ -25,6 +26,14 @@ func WithSignedValue(value string, signer crypt.Signer) x.Option[*http.Cookie] {
 	return WithValue(fmt.Sprintf("%v%v%v", value, delimiter, string(signature)))
 }
 
+func WithEncodedValue(data []byte, encoding *base64.Encoding) x.Option[*http.Cookie] {
+	return WithValue(encoding.EncodeToString(data))
+}
+
+func WithBase64Value(data []byte) x.Option[*http.Cookie] {
+	return WithEncodedValue(data, base64.URLEncoding)
+}
+
 func WithPath(value string) x.Option[*http.Cookie] {
 	return With(func(c *http.Cookie) {
 		c.Path = value
pkg/cookie/option_test.go
@@ -3,6 +3,7 @@ package cookie
 import (
 	"crypto/hmac"
 	"crypto/sha256"
+	"encoding/base64"
 	"fmt"
 	"net/http"
 	"testing"
@@ -11,6 +12,7 @@ import (
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
 	"github.com/xlgmokha/x/pkg/crypt"
+	"github.com/xlgmokha/x/pkg/pls"
 	"github.com/xlgmokha/x/pkg/x"
 )
 
@@ -79,4 +81,13 @@ func TestOption(t *testing.T) {
 		assert.Equal(t, expected, cookie.Value)
 		assert.True(t, hmac.Equal([]byte(expected), []byte(cookie.Value)))
 	})
+
+	t.Run("WithBase64EncodedValue", func(t *testing.T) {
+		value := x.Must(pls.GenerateRandomBytes(32))
+		cookie := New("session", WithBase64Value(value))
+
+		require.NotNil(t, cookie)
+		expected := base64.URLEncoding.EncodeToString(value)
+		assert.Equal(t, expected, cookie.Value)
+	})
 }