Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pointer structs not created with env prefixes #234

Closed
mrsimonemms opened this issue Aug 31, 2022 · 4 comments
Closed

Pointer structs not created with env prefixes #234

mrsimonemms opened this issue Aug 31, 2022 · 4 comments

Comments

@mrsimonemms
Copy link

Following the issue raised in #202, if a pointer struct is used then the default object is not created - this is different to a non-pointer object. See the following example:

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"

	"github.com/caarlos0/env/v6"
)

type Test struct {
	Str string `env:"TEST"`
}
type ComplexConfig struct {
	Foo   *Test `envPrefix:"FOO_"`
	Bar   Test  `envPrefix:"BAR_"`
	Clean *Test
}

func main() {
	os.Setenv("FOO_TEST", "kek")
	os.Setenv("BAR_TEST", "lel")

	cfg := ComplexConfig{}
	err := env.Parse(&cfg)
	if err != nil {
		log.Fatal(err)
	}
	confBytes, _ := json.Marshal(cfg)
	fmt.Printf("%s", confBytes)
}

This results in:

{"Foo":null,"Bar":{"Str":"lel"},"Clean":null}

Notice how Foo is null, but Bar has the object created.

@caarlos0
Copy link
Owner

yes, pointers need to be non-nil, otherwise env ignores them... I can't quite remember exactly why, will take a look when I have some time.

@caarlos0
Copy link
Owner

caarlos0 commented Jan 6, 2023

https://github.com/caarlos0/env/compare/nilptr?expand=1

this would init the pointers, but break a lot of other things... would need to investigate more... some other day

in the meantime, if anyone knows a lot about the reflect pkg and wants to take a look

@NithinGudla
Copy link
Contributor

Hi @caarlos0 ,

I tried to fix the nil pointer issue,
Please take a look at this pull request once when you get some time,

#306

Changes:

  1. If a struct pointer field is nil, it will be initialised first & then used for further processing.
  2. If custom parse function is defined on any type, we don't traverse through the struct recursively.

Thanks

@caarlos0
Copy link
Owner

thanks @NithinGudla!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants