Skip to content

Decoding bytearray inputs #73

Open
@vkrizan

Description

@vkrizan

Hello.

A Decode getting a bytearray ([]byte) input from a stringified number does an assumed pre-conversion before writing it into the output. The output type isn't respected. This is troublesome when decoding base64 inputs (e.g. k8s Secrets data).

Input:

[]byte(strconv.Itoa(1234))

Output types:

string
int

Minimal test:

package main

import (
	"fmt"
	"strconv"

	"github.com/go-viper/mapstructure/v2"
)

func main() {
	var o1 string
	var o2 int

	in := []byte(strconv.Itoa(1234))
	fmt.Printf("Input: %#v\n", in)

	for _, out := range []interface{}{&o1, &o2} {
		fmt.Printf("\nOutput type: %T\n", out)
		err := mapstructure.Decode(in, out)
		if err != nil {
			fmt.Printf("Error: %+v\n", err)
		} else {
			fmt.Printf("Output: %#v\n", out)
		}
	}
}

Output:

Input: []byte{0x31, 0x32, 0x33, 0x34}

Output type: *string
Error: '' expected type 'string', got unconvertible type '[]uint8', value: '[49 50 51 52]'

Output type: *int
Error: '' expected type 'int', got unconvertible type '[]uint8', value: '[49 50 51 52]'

Is this a bug, or have I not understood the mapstructure decoding correctly?

Workaround: use mapstructure.WeakDecode() instead.

Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions