github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/uri/uri.go (about) 1 // Copyright 2023 The GitBundle Inc. All rights reserved. 2 // Copyright 2017 The Gitea Authors. All rights reserved. 3 // Use of this source code is governed by a MIT-style 4 // license that can be found in the LICENSE file. 5 6 package uri 7 8 import ( 9 "fmt" 10 "io" 11 "net/http" 12 "net/url" 13 "os" 14 "strings" 15 ) 16 17 // ErrURISchemeNotSupported represents a scheme error 18 type ErrURISchemeNotSupported struct { 19 Scheme string 20 } 21 22 func (e ErrURISchemeNotSupported) Error() string { 23 return fmt.Sprintf("Unsupported scheme: %v", e.Scheme) 24 } 25 26 // Open open a local file or a remote file 27 func Open(uriStr string) (io.ReadCloser, error) { 28 u, err := url.Parse(uriStr) 29 if err != nil { 30 return nil, err 31 } 32 switch strings.ToLower(u.Scheme) { 33 case "http", "https": 34 f, err := http.Get(uriStr) 35 if err != nil { 36 return nil, err 37 } 38 return f.Body, nil 39 case "file": 40 return os.Open(u.Path) 41 default: 42 return nil, ErrURISchemeNotSupported{Scheme: u.Scheme} 43 } 44 }