Commit 6ca129da authored by vicotor's avatar vicotor

update create website

parent 52db8d1c
...@@ -8,8 +8,10 @@ import ( ...@@ -8,8 +8,10 @@ import (
"github.com/xueqianlu/caddyproxy/utils" "github.com/xueqianlu/caddyproxy/utils"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"os"
"path/filepath" "path/filepath"
"text/template" "text/template"
"time"
) )
type CaddyAPI struct { type CaddyAPI struct {
...@@ -115,9 +117,44 @@ func (c *CaddyAPI) buildPayloadForForwardWebsite(domain string, target string) ( ...@@ -115,9 +117,44 @@ func (c *CaddyAPI) buildPayloadForForwardWebsite(domain string, target string) (
return buffer.String(), nil return buffer.String(), nil
} }
func pathExist(path string) bool {
_, err := os.Stat(path)
if os.IsNotExist(err) {
return false
}
return true
}
func (c *CaddyAPI) CreateWebsite(domain string, resource string) error { func (c *CaddyAPI) CreateWebsite(domain string, resource string) error {
// unzip resource to the website root directory. // unzip resource to the website root directory.
websiteRoot := filepath.Join(c.RootDir, "websites", domain) websiteRoot := filepath.Join(c.RootDir, "websites", domain)
rollback := false
success := false
backupname := fmt.Sprintf("%s.%s.bak", websiteRoot, time.Now().Format("2006-01-02-15-04-05"))
defer func() {
if !success && rollback {
os.Remove(websiteRoot)
if err := os.Rename(backupname, websiteRoot); err != nil {
log.WithFields(log.Fields{
"backup": backupname,
"website": websiteRoot,
}).WithError(err).Error("failed to rollback website")
}
}
}()
// if websiteRoot exist, remove it first. and add rollback flag.
if pathExist(websiteRoot) {
// backup old website.
if err := os.Rename(websiteRoot, backupname); err != nil {
log.WithFields(log.Fields{
"backup": backupname,
"website": websiteRoot,
}).WithError(err).Error("failed to backup website")
return err
} else {
rollback = true
}
}
if err := utils.Unzip(resource, websiteRoot); err != nil { if err := utils.Unzip(resource, websiteRoot); err != nil {
return err return err
} }
...@@ -138,7 +175,7 @@ func (c *CaddyAPI) CreateWebsite(domain string, resource string) error { ...@@ -138,7 +175,7 @@ func (c *CaddyAPI) CreateWebsite(domain string, resource string) error {
if err := c.put(path, []byte(payload)); err != nil { if err := c.put(path, []byte(payload)); err != nil {
return err return err
} }
success = true
return nil return nil
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment