[ 1. 환경 세팅 : Config ]
import “toml” (env와 동일한 역할)
go get
github.com/naoina/toml
⇒ 해당 패키지가 설치되어야 config 사용 가능
func NewConfig(filePath string) *Config {
c := new(Config)
var c *Config
// c := &Config{}
기본적으로 NewConfig의 Return은 복제보다는 포인터를 이용한 원본 전달
c := new(Config)
와var c *Config
이 두 개는 각각- zero value와 nil을 값으로 가지기 때문에 후에 값을 넣어줘야 함
c:= &Config{ }
방식은 원하는 값으로 초기화와 동시에 생성이 가능하지만 타입 추론 에러가 발생하기도 해서 비선호
[ 2. Decode ]
func NewConfig(filePath string) *Config {
c := new(Config)
if file, err := os.Open(filePath); err == nil {
panic(err)
} else if err = toml.NewDecoder(file).Decode(c); err != nil {
panic(err)
} else {
return c
}
}
toml.NewDecoder(file).Decode(c)
gotype Config struct { Server struct { Port string } }
go[Server] Port = ":8080"
⇒ 위와 같은 파일을 읽어 Decode해서 구조체 c에 값을 채움
[ 3. Cmd(command) ]
type Cmd struct {
config *config.Config
}
- *config.Config는 패키지 config를 포인터 참조한 Config(원래 포인터)
응용
go run ./init --port 8081 --config ./init/conf.toml
gofunc main() { var port = flag.Int("port", 8080, "not found") var config = flag.String("config", "./config.toml", "not found") flag.Parse() cmd.NewCmd(*config) fmt.Println("포트", *port) fmt.Println("설정 파일:", *config)
⇒ flag(커멘드라인 옵션) 선언 + flag.Parse( )를 통해 기본값 or 인자 설정 가능
- 주의 : go run main.go로 해버리면 주변 파일을 이용 불가능