mkideal / cli

CLI - A package for building command line app with go
MIT License
732 stars 43 forks source link

Please expose the json conf reading function #22

Closed suntong closed 8 years ago

suntong commented 8 years ago

Hiya,

Please expose the json conf reading function, i.e., the function behind the Self ... json:"-" parser:"jsonfile"... support.

I found myself need to deal with different json conf files for exactly the same functionality. So far, I've duplicated the CLI twice and now three times, just in order to to take advantage of the auto-magical "Self" reading feature.

Now I need to do more. So, once I can use the function to read different json conf files, I can consolidate those three (and more) sub commands into one.

Thanks

mkideal commented 8 years ago

So easy to read json file:

func (p JSONFileParser) Parse(s string) error {
    f, err := os.Open(s)
    if err != nil {
        return err
    }
    return json.NewDecoder(f).Decode(p.ptr)
}
suntong commented 8 years ago

Hmm..., agree, it's easy to read json files. I'm just thinking, from the completeness point of view, CLI should expose how to update the CLI structure from json files, giving it a standard so that everyone can following, not everyone doing it in their own ways.

BTW, you demo code only deals with json file, but you've left out how to update the CLI structure from json file right?

mkideal commented 8 years ago

I add functions: ReadJSON and ReadJSONFromFile

func ReadJSON(r io.Reader, argv interface{}) error {
    return json.NewDecoder(r).Decode(argv)
}

func ReadJSONFromFile(filename string, argv interface{}) error {
    file, err := os.Open(filename)
    if err == nil {
        err = ReadJSON(file, argv)
    }
    return err
}

Both two can update argv from json data. See commit 617d581

suntong commented 8 years ago

Thank you VERY MUCH!

suntong commented 8 years ago

It doesn't really matter but it is better to close the file in ReadJSONFromFile().

Ref: https://github.com/go-jsonfile/jsonfile/blob/master/jsonfile.go

Note the line,

// Credits: Mkideal Wang https://github.com/mkideal/cli/issues/22

mkideal commented 8 years ago

Thanks!