use []byte for binary payloads

This commit is contained in:
1e99 2024-11-08 16:02:26 +01:00
parent d6e016719a
commit 0381cb13ba
2 changed files with 7 additions and 12 deletions

View file

@ -12,7 +12,8 @@ import (
func CreatePassword(store storage.Store, maxLength int, encoding *base64.Encoding) http.HandlerFunc { func CreatePassword(store storage.Store, maxLength int, encoding *base64.Encoding) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) { return func(res http.ResponseWriter, req *http.Request) {
var reqBody struct { var reqBody struct {
Password string `json:"password"` // Go automatically decodes byte arrays using Base64
Password []byte `json:"password"`
ExpiresIn time.Duration `json:"expires-in"` ExpiresIn time.Duration `json:"expires-in"`
} }
err := json.NewDecoder(req.Body).Decode(&reqBody) err := json.NewDecoder(req.Body).Decode(&reqBody)
@ -21,13 +22,7 @@ func CreatePassword(store storage.Store, maxLength int, encoding *base64.Encodin
return return
} }
password, err := encoding.DecodeString(reqBody.Password) if len(reqBody.Password) > maxLength {
if err != nil {
http.Error(res, "Bad base64 encoding", http.StatusBadRequest)
return
}
if len(password) > maxLength {
http.Error(res, "Password too long", 413) // Payload Too Large http.Error(res, "Password too long", 413) // Payload Too Large
return return
} }
@ -44,7 +39,7 @@ func CreatePassword(store storage.Store, maxLength int, encoding *base64.Encodin
} }
id, err := store.Create( id, err := store.Create(
password, reqBody.Password,
time.Now().Add(expiresIn), time.Now().Add(expiresIn),
) )
switch { switch {

View file

@ -27,11 +27,11 @@ func GetPassword(store storage.Store, encoding *base64.Encoding) http.HandlerFun
return return
} }
encodedPassword := encoding.EncodeToString(password)
resBody := struct { resBody := struct {
Password string `json:"password"` // Go automatically encodes byte arrays using Base64
Password []byte `json:"password"`
}{ }{
Password: encodedPassword, Password: password,
} }
err = json.NewEncoder(res).Encode(&resBody) err = json.NewEncoder(res).Encode(&resBody)
if err != nil { if err != nil {