Files
NanoKVM-MIRROR/server/utils/http.go
wj-xiao 6eb4a4ea62 update version to 2.1.6
feat: support downloading image from online URL
feat: add keyboard shortcut Ctrl+Alt+Del
fix: fix the CSRF issue
perf: add an option to configure custom ICE servers
perf: removed unnecessary modifications to DNS configuration
perf: add an SSH enable/disable toggle in the web UI
perf: add a Tailscale enable/disable toggle in the web UI
perf: download Tailscale installation package from the official source
perf: automatic enable/disable GOMEMLIMIT on tailscale start/stop
perf: add JWT configuration
perf: implement secure password storage using bcrypt hashing
perf: implement integrity checks for online updates
refactor: refactor HDMI module and remove the dependency libmaixcam_lib.so
refactor: web terminal use pty instead of SSH
refactor: move Tailscale APIs from the network module to the extensions module
2025-02-14 14:18:13 +08:00

57 lines
1.4 KiB
Go

package utils
import (
"errors"
"io"
"net/http"
"os"
"path/filepath"
log "github.com/sirupsen/logrus"
)
func Download(req *http.Request, target string) error {
log.Debugf("downloading %s to %s", req.URL.String(), target)
err := os.MkdirAll(filepath.Dir(target), 0o755)
if err != nil {
log.Errorf("create dir %s err: %s", filepath.Dir(target), err)
return err
}
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("request error: %s", err)
return err
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
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" && contentType != "application/gzip" {
log.Debugf("unexpected content-type, it should be either octet-stream or (g)zip, but got: %s", contentType)
return errors.New("unsupported content type")
}
_, err = io.Copy(out, resp.Body)
if err != nil {
log.Errorf("download file to %s err: %s", target, err)
return err
}
return nil
}