github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/cli/altsrc/yaml_file_loader.go (about) 1 // Disabling building of yaml support in cases where golang is 1.0 or 1.1 2 // as the encoding library is not implemented or supported. 3 4 // +build go1.2 5 6 package altsrc 7 8 import ( 9 "fmt" 10 "io/ioutil" 11 "net/http" 12 "net/url" 13 "os" 14 15 "github.com/insionng/yougam/libraries/cli" 16 17 "github.com/insionng/yougam/libraries/yaml.v2" 18 ) 19 20 type yamlSourceContext struct { 21 FilePath string 22 } 23 24 // NewYamlSourceFromFile creates a new Yaml InputSourceContext from a filepath. 25 func NewYamlSourceFromFile(file string) (InputSourceContext, error) { 26 ysc := &yamlSourceContext{FilePath: file} 27 var results map[string]interface{} 28 err := readCommandYaml(ysc.FilePath, &results) 29 if err != nil { 30 return nil, fmt.Errorf("Unable to load Yaml file '%s': inner error: \n'%v'", ysc.FilePath, err.Error()) 31 } 32 33 return &MapInputSource{valueMap: results}, nil 34 } 35 36 // NewYamlSourceFromFlagFunc creates a new Yaml InputSourceContext from a provided flag name and source context. 37 func NewYamlSourceFromFlagFunc(flagFileName string) func(context *cli.Context) (InputSourceContext, error) { 38 return func(context *cli.Context) (InputSourceContext, error) { 39 filePath := context.String(flagFileName) 40 return NewYamlSourceFromFile(filePath) 41 } 42 } 43 44 func readCommandYaml(filePath string, container interface{}) (err error) { 45 b, err := loadDataFrom(filePath) 46 if err != nil { 47 return err 48 } 49 50 err = yaml.Unmarshal(b, container) 51 if err != nil { 52 return err 53 } 54 55 err = nil 56 return 57 } 58 59 func loadDataFrom(filePath string) ([]byte, error) { 60 u, err := url.Parse(filePath) 61 if err != nil { 62 return nil, err 63 } 64 65 if u.Host != "" { // i have a host, now do i support the scheme? 66 switch u.Scheme { 67 case "http", "https": 68 res, err := http.Get(filePath) 69 if err != nil { 70 return nil, err 71 } 72 return ioutil.ReadAll(res.Body) 73 default: 74 return nil, fmt.Errorf("scheme of %s is unsupported", filePath) 75 } 76 } else if u.Path != "" { // i dont have a host, but I have a path. I am a local file. 77 if _, notFoundFileErr := os.Stat(filePath); notFoundFileErr != nil { 78 return nil, fmt.Errorf("Cannot read from file: '%s' because it does not exist.", filePath) 79 } 80 return ioutil.ReadFile(filePath) 81 } else { 82 return nil, fmt.Errorf("unable to determine how to load from path %s", filePath) 83 } 84 }