local-server/cmd/dkl-local-server/ws-configs.go

76 lines
1.1 KiB
Go
Raw Normal View History

2019-02-04 02:56:43 +00:00
package main
import (
"compress/gzip"
"io"
"io/ioutil"
"os"
"path/filepath"
restful "github.com/emicklei/go-restful"
)
func wsUploadConfig(req *restful.Request, resp *restful.Response) {
2019-02-04 03:39:37 +00:00
body := req.Request.Body
2019-02-04 02:56:43 +00:00
2019-02-04 03:39:37 +00:00
err := writeNewConfig(body)
body.Close()
2019-02-04 02:56:43 +00:00
2019-02-04 03:39:37 +00:00
if err != nil {
wsError(resp, err)
2019-02-04 02:56:43 +00:00
}
2019-02-04 03:39:37 +00:00
}
2019-02-04 02:56:43 +00:00
2019-02-04 03:39:37 +00:00
func writeNewConfig(reader io.Reader) (err error) {
2019-02-04 02:56:43 +00:00
out, err := ioutil.TempFile(*dataDir, ".config-upload")
if err != nil {
return
}
defer os.Remove(out.Name())
2019-02-04 03:41:51 +00:00
_, err = io.Copy(out, reader)
2019-02-04 02:56:43 +00:00
out.Close()
if err != nil {
return
}
archivesPath := filepath.Join(*dataDir, "archives")
cfgPath := configFilePath()
err = os.MkdirAll(archivesPath, 0700)
if err != nil {
return
}
2019-02-04 03:39:37 +00:00
backupPath := filepath.Join(archivesPath, "config."+ulid()+".yaml.gz")
2019-02-04 02:56:43 +00:00
2019-02-04 03:39:37 +00:00
bck, err := os.Create(backupPath)
if err != nil {
return
}
2019-02-04 02:56:43 +00:00
2019-02-04 03:39:37 +00:00
defer bck.Close()
2019-02-04 02:56:43 +00:00
2019-02-04 03:39:37 +00:00
in, err := os.Open(cfgPath)
if err != nil {
2019-02-04 02:56:43 +00:00
return
2019-02-04 03:39:37 +00:00
}
2019-02-04 02:56:43 +00:00
2019-02-04 03:39:37 +00:00
gz, err := gzip.NewWriterLevel(bck, 2)
2019-02-04 02:56:43 +00:00
if err != nil {
return
}
2019-02-04 03:39:37 +00:00
_, err = io.Copy(gz, in)
gz.Close()
in.Close()
2019-02-04 02:56:43 +00:00
if err != nil {
return
}
2019-02-04 03:39:37 +00:00
err = os.Rename(out.Name(), cfgPath)
return
2019-02-04 02:56:43 +00:00
}