Skip to content

Commit

Permalink
Base64 Support (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
bbengfort authored Jul 22, 2023
1 parent 6050835 commit c603e5e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
22 changes: 17 additions & 5 deletions parse/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ an environment variable or from a struct field) into a Go type for the struct.
package parse

import (
"encoding/base64"
"fmt"
"reflect"
"strconv"
Expand Down Expand Up @@ -54,8 +55,10 @@ func Parse(value string, field reflect.Value) error {
}

if bin := BinaryUnmarshalerFromValue(field); bin != nil {
// TODO: should we decode base64 or hex data here?
if err := bin.UnmarshalBinary([]byte(value)); err != nil {
// Try to decode base64 data from the value otherwise convert to []byte
data := toBytes(value)

if err := bin.UnmarshalBinary(data); err != nil {
return &errors.ParseError{
Source: "BinaryUnmarshaler",
Type: field.Type().Name(),
Expand Down Expand Up @@ -132,8 +135,10 @@ func ParseField(value string, field *structs.Field) error {
}

if bin := BinaryUnmarshalerFrom(field); bin != nil {
// TODO: should we decode base64 or hex data here?
if err := bin.UnmarshalBinary([]byte(value)); err != nil {
// Try to decode base64 data from the value otherwise convert to []byte
data := toBytes(value)

if err := bin.UnmarshalBinary(data); err != nil {
return &errors.ParseError{
Source: "BinaryUnmarshaler",
Field: field.Name(),
Expand Down Expand Up @@ -212,7 +217,7 @@ func parse(value string, field reflect.Value) (err error) {
case reflect.Slice:
sl := reflect.MakeSlice(typ, 0, 0)
if typ.Elem().Kind() == reflect.Uint8 {
sl = reflect.ValueOf([]byte(value))
sl = reflect.ValueOf(toBytes(value))
} else if strings.TrimSpace(value) != "" {
vals := strings.Split(value, ",")
sl = reflect.MakeSlice(typ, len(vals), len(vals))
Expand Down Expand Up @@ -252,3 +257,10 @@ func parse(value string, field reflect.Value) (err error) {

return nil
}

func toBytes(v string) []byte {
if data, err := base64.StdEncoding.DecodeString(v); err == nil {
return data
}
return []byte(v)
}
2 changes: 2 additions & 0 deletions parse/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ func TestParseField(t *testing.T) {
"LinkTo": {"https://rotational.io", &CustomURL{Value: r8l}},
"EmptyMap": {"", map[string]int{}},
"EmptySlice": {"", []string{}},
"ByteSlice": {"n2LeUR98zrfDdAcJAu58Eg==", []byte{0x9f, 0x62, 0xde, 0x51, 0x1f, 0x7c, 0xce, 0xb7, 0xc3, 0x74, 0x7, 0x9, 0x2, 0xee, 0x7c, 0x12}},
}

for _, field := range s.Fields() {
Expand Down Expand Up @@ -103,6 +104,7 @@ type Specification struct {
LinkTo *CustomURL
EmptyMap map[string]int
EmptySlice []string
ByteSlice []byte
}

type Color [3]uint8
Expand Down

0 comments on commit c603e5e

Please sign in to comment.