mirror of
https://github.com/sipeed/NanoKVM.git
synced 2026-09-13 03:19:45 -05:00
Slightly refactor nanokvm code
* Add ability to properly configure logrus (e.x. specify output file) * Make the code slightly more ideomatic (sort imports, etc) * Replace some of the shell calls with equivalent native code * Fix update process * Improve error handling (handle 2 previously unhandled errors) * Add locking for HID operations and make a HID-operations struct a singleton
This commit is contained in:
@@ -2,34 +2,48 @@ package utils
|
||||
|
||||
import (
|
||||
"errors"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func Download(req *http.Request, target string) error {
|
||||
out, err := os.OpenFile(target, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
|
||||
log.Debugf("downloading %s to %s", req.URL.String(), target)
|
||||
err := os.MkdirAll(filepath.Dir(target), 0o755)
|
||||
if err != nil {
|
||||
log.Errorf("create file %s err: %s", target, err)
|
||||
log.Errorf("create dir %s err: %s", filepath.Dir(target), err)
|
||||
return err
|
||||
}
|
||||
defer out.Close()
|
||||
out, err := os.OpenFile(target, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o755)
|
||||
if err != nil {
|
||||
log.Errorf("cannot create file '%s', error: %s", target, err)
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
_ = out.Close()
|
||||
}()
|
||||
|
||||
resp, err := (&http.Client{}).Do(req)
|
||||
if err != nil {
|
||||
log.Errorf("download file err: %s", err)
|
||||
log.Errorf("request error: %s", err)
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return errors.New("request error")
|
||||
log.Errorf("request failed, status code: %d", resp.StatusCode)
|
||||
return errors.New("update website is inaccessible right now")
|
||||
}
|
||||
|
||||
contentType := resp.Header.Get("Content-Type")
|
||||
if contentType != "application/octet-stream" && contentType != "application/zip" {
|
||||
return errors.New("download error")
|
||||
log.Debugf("unexpected content-type, it should be either octet-stream or zip, but got: %s", contentType)
|
||||
return errors.New("unsupported content type")
|
||||
}
|
||||
|
||||
_, err = io.Copy(out, resp.Body)
|
||||
|
||||
Reference in New Issue
Block a user