Go언어 golang
golang JSON 설정 파일 로더 / JSON 주석 처리
미래의 고
2023. 3. 23. 21:52
개발을 배포할때 설정 파일을 json타입으로 할때가 있습니다.
사용법 혹은 메뉴얼을 작성해서 같이 주긴 하지만, json에 설명을 달아주는게 본인을 위해서도 편합니다.
그래서 주석을 허용하는 reader를 해보려 합니다.
github.com/wuxiangzhou2010/jsonuncommenter 을 사용해서 진행하였습니다.


이걸 써보니 문제가 있습니다. node_name쪽에 주석을 넣어보니 동작 안합니다.
다음포스팅에서는 직접 만들어 봐야겠습니다.
package main
import (
"encoding/json"
"fmt"
"os"
"path"
"github.com/wuxiangzhou2010/jsonuncommenter"
)
type Config struct {
ServiceIp string `json:"service_ip"`
NodeName string `json:"node_name"`
}
func main() {
cwd, err := os.Getwd()
if err != nil {
panic(err)
}
f, err := os.Open(path.Join(cwd, `config.json`))
if err != nil {
panic(err)
}
defer f.Close()
newReader := jsonuncommenter.RemoveComment(f)
jsonParser := json.NewDecoder(newReader)
var config Config
jsonParser.Decode(&config)
fmt.Printf("%+v", config)
}