cast icon indicating copy to clipboard operation
cast copied to clipboard

Support for ToSliceMapStringString in cast useful or better implement myself?

Open andygrunwald opened this issue 8 years ago • 0 comments

Hey,

thanks to cast. I found this library through viper. I use viper to read a JSON configuration. It works great so far. Viper has various support functions to get pre casted values. See Getting Values From Viper.

Next to standard types like string or bool is has support for GetStringMapStringSlice (which falls back to this library here).

Now my configuration file looks like this:

{
    "repositories": [
      {
        "name": "myvendor/package",
        "url": "git@othervcs:myvendor/package.git"
      }
    ],
    "dir": "/var/foo",
    "mirror": true,
    ...
}

The repositories would be a []map[string]string. I need to do a few operations on this construct like "Is this repository is configured? If yes, is there a url?". To solve this question i do it like

func GetRepositoryURLOfPackage(n string) (*url.URL, error) {
	repositories := viper.Get("repositories")

	repositoriesSlice := repositories.([]interface{})
	if (len(repositoriesSlice) == 0) {
		return nil, errors.New("No repositories configured.")
	}

	for _, repoEntry := range repositoriesSlice {
		repoEntryMap := repoEntry.(map[string]interface{})
		if val, ok := repoEntryMap["name"]; !ok {
			if val.(string) == n {
				// TODO: Check if key "url" exists
				return repoEntryMap["url"].(string)
			}
		}
	}

	return nil, fmt.Errorf("No repository url found for package %s", n)
}

It works. A better solution would be to implement a ToStringMapStringSlice function.

Now the question: Do you see the need or does it make sense to implement a ToStringMapStringSlice into cast and enable this in viper as well? Or should i implement it in my code and leave it there as a custom impl.?

The reason i ask: There are multiple other usecases where those data structures are not implemented by cast like GetIntMapStringSlice, etc. So it would be "never" complete.

andygrunwald avatar Jan 08 '17 16:01 andygrunwald