github.com/yaegashi/msgraph.go@v0.1.4/msauth/storage.go (about) 1 package msauth 2 3 import ( 4 "bytes" 5 "fmt" 6 "io/ioutil" 7 "net/http" 8 "net/url" 9 "os" 10 "strings" 11 ) 12 13 // ReadLocation reads data from file with path or URL 14 func ReadLocation(loc string) ([]byte, error) { 15 u, err := url.Parse(loc) 16 if err != nil { 17 return nil, err 18 } 19 switch u.Scheme { 20 case "", "file": 21 return ioutil.ReadFile(u.Path) 22 case "http", "https": 23 res, err := http.Get(loc) 24 if err != nil { 25 return nil, err 26 } 27 defer res.Body.Close() 28 if res.StatusCode != http.StatusOK { 29 return nil, fmt.Errorf("%s", res.Status) 30 } 31 b, err := ioutil.ReadAll(res.Body) 32 if err != nil { 33 return nil, err 34 } 35 return b, nil 36 } 37 return nil, fmt.Errorf("Unsupported location to load: %s", loc) 38 } 39 40 // WriteLocation writes data to file with path or URL 41 func WriteLocation(loc string, b []byte, m os.FileMode) error { 42 u, err := url.Parse(loc) 43 if err != nil { 44 return err 45 } 46 switch u.Scheme { 47 case "", "file": 48 return ioutil.WriteFile(u.Path, b, m) 49 case "http", "https": 50 if strings.HasSuffix(u.Host, ".blob.core.windows.net") { 51 // Azure Blob Storage URL with SAS assumed here 52 cli := &http.Client{} 53 req, err := http.NewRequest(http.MethodPut, loc, bytes.NewBuffer(b)) 54 if err != nil { 55 return err 56 } 57 req.Header.Set("x-ms-blob-type", "BlockBlob") 58 res, err := cli.Do(req) 59 if err != nil { 60 return err 61 } 62 defer res.Body.Close() 63 if res.StatusCode != http.StatusCreated { 64 return fmt.Errorf("%s", res.Status) 65 } 66 return nil 67 } 68 } 69 return fmt.Errorf("Unsupported location to save: %s", loc) 70 }