github.com/tomwright/dasel@v1.27.3/internal/selfupdate/impl.go (about) 1 package selfupdate 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io" 7 "net/http" 8 "os" 9 "os/exec" 10 ) 11 12 func executeCmd(name string, arg ...string) ([]byte, error) { 13 return exec.Command(name, arg...).Output() 14 } 15 16 func fetchGitHubRelease(httpClient *http.Client, user string, repo string, tag string) (*Release, error) { 17 if tag != "latest" { 18 tag = fmt.Sprintf("tags/%s", tag) 19 } 20 url := fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/%s", user, repo, tag) 21 22 req, err := http.NewRequest(http.MethodGet, url, nil) 23 if err != nil { 24 return nil, fmt.Errorf("could not create request to get latest release: %w", err) 25 } 26 27 resp, err := httpClient.Do(req) 28 if err != nil { 29 return nil, fmt.Errorf("could not perform request to get latest release: %w", err) 30 } 31 defer resp.Body.Close() 32 33 if resp.StatusCode != 200 { 34 return nil, nil 35 } 36 37 respBytes, err := io.ReadAll(resp.Body) 38 if err != nil { 39 return nil, fmt.Errorf("could not read response bytes: %w", err) 40 } 41 42 release := &Release{} 43 if err := json.Unmarshal(respBytes, release); err != nil { 44 return nil, fmt.Errorf("could not parse response: %w", err) 45 } 46 47 return release, nil 48 } 49 50 func downloadFile(url string, dest string) error { 51 resp, err := http.Get(url) 52 if err != nil { 53 return err 54 } 55 defer resp.Body.Close() 56 57 out, err := os.Create(dest) 58 if err != nil { 59 return err 60 } 61 defer out.Close() 62 63 // Write the body to file 64 _, err = io.Copy(out, resp.Body) 65 if err != nil { 66 return err 67 } 68 69 return nil 70 }