caarlos0 / env

A simple, zero-dependencies library to parse environment variables into structs
https://pkg.go.dev/github.com/caarlos0/env/v11
MIT License
4.78k stars 245 forks source link

[Issue|Question] Regarding `map[string][]string` #308

Closed eltonsv closed 3 months ago

eltonsv commented 4 months ago

Hi folks, we noticed that for configs with JSON pointing to map[string][]string, it fails with the error, and we are unable to parse these JSONs. Could you please help us if there is something wrong with the implementation? Added a test that replicates this below:

package app

import (
    "encoding/json"
    "testing"

    "github.com/caarlos0/env/v10"
    "github.com/stretchr/testify/assert"
)

type AppConfigTest struct {
    FinanceAllowedRoles FinanceRolesMapTest `env:"FINANCE_ALLOWED_ROLES"`
}

type FinanceRolesMapTest map[string][]string

func (rc *FinanceRolesMapTest) UnmarshalText(b []byte) error {
    return json.Unmarshal(b, &rc)
}

func TestParseConfig(t *testing.T) {
    t.Setenv("FINANCE_ALLOWED_ROLES", `{"DEFAULT":["ADMIN"]}`)
    _, err := parseConfigTest()
    assert.Equal(t, nil, err)
}

func parseConfigTest() (AppConfigTest, error) {
    var config AppConfigTest

    if err := env.Parse(&config); err != nil {
        return AppConfigTest{}, err
    }

    return config, nil
}

yields

=== RUN   TestParseConfig
    config_test.go:24: 
            Error Trace:    /Users/e.savio/go/dh/dh-vt-kratos/go-services/vp-finance-backend/app/config_test.go:24
            Error:          Not equal: 
                            expected: <nil>(<nil>)
                            actual  : env.AggregateError(env.AggregateError{Errors:[]error{env.ParseError{Name:"FinanceAllowedRoles", Type:(*reflect.rtype)(0x1c3ce80), Err:(*json.UnmarshalTypeError)(0xc000196820)}}})
            Test:           TestParseConfig
--- FAIL: TestParseConfig (0.00s)

Expected :<nil>(<nil>)
Actual   :env.AggregateError(env.AggregateError{Errors:[]error{env.ParseError{Name:"FinanceAllowedRoles", Type:(*reflect.rtype)(0x1c3ce80), Err:(*json.UnmarshalTypeError)(0xc000196820)}}})
FAIL

Process finished with the exit code 1

Do you know if there is something that needs to be changed to support this in the json/implementation, or if this is an issue in the parsing?

Thank you so much

caarlos0 commented 3 months ago

hey! you're on the right track, but the unmarshal impl needs to be a bit different afaik.

I pushed a test/example in c4db909