all repos — flounder @ 3384eb4f1e94daa548dadcd5d074d59edc0c7eb0

A small site builder for the Gemini protocol

Add archive handler
alex wennerberg alex@alexwennerberg.com
Sat, 31 Oct 2020 10:23:07 -0700
commit

3384eb4f1e94daa548dadcd5d074d59edc0c7eb0

parent

744622624fd556c99fd8914824f2f0a6cba849ae

3 files changed, 80 insertions(+), 0 deletions(-)

jump to
M http.gohttp.go

@@ -213,6 +213,23 @@ }{c.Host, c.SiteTitle, authUser, files, authd, isAdmin}

_ = t.ExecuteTemplate(w, "my_site.html", data) } +func archiveHandler(w http.ResponseWriter, r *http.Request) { + authd, authUser, _ := getAuthUser(r) + if !authd { + renderError(w, "403: Forbidden", 403) + return + } + if r.Method == "GET" { + userFolder := filepath.Join(c.FilesDirectory, filepath.Clean(authUser)) + err := zipit(userFolder, w) + if err != nil { + log.Println(err) + renderError(w, InternalServerErrorMsg, 500) + return + } + + } +} func loginHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { // show page

@@ -450,6 +467,7 @@ port := c.HttpPort

serveMux.HandleFunc(hostname+"/", rootHandler) serveMux.HandleFunc(hostname+"/my_site", mySiteHandler) + serveMux.HandleFunc(hostname+"/my_site/flounder-archive.zip", archiveHandler) serveMux.HandleFunc(hostname+"/admin", adminHandler) serveMux.HandleFunc(hostname+"/edit/", editFileHandler) serveMux.HandleFunc(hostname+"/upload", uploadFilesHandler)
M templates/my_site.htmltemplates/my_site.html

@@ -52,4 +52,6 @@ <form action="/upload" enctype="multipart/form-data" method="POST">

<input type="file" id="myFile" name="file" multiple /> <input type="submit" value="Upload file" class="button" /> </form> +<br> +<p><a href="/my_site/flounder-archive.zip">Download site archive</a></p> {{template "footer" .}}
M utils.goutils.go

@@ -1,8 +1,12 @@

package main import ( + "archive/zip" "fmt" + "io" + "os" "path" + "path/filepath" "strings" "time" )

@@ -41,3 +45,59 @@ return fmt.Errorf("File too large. File was %d bytes, Max file size is %d", len(fileBytes), c.MaxFileSize)

} return nil } + +func zipit(source string, target io.Writer) error { + archive := zip.NewWriter(target) + + info, err := os.Stat(source) + if err != nil { + return nil + } + + var baseDir string + if info.IsDir() { + baseDir = filepath.Base(source) + } + + filepath.Walk(source, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + + header, err := zip.FileInfoHeader(info) + if err != nil { + return err + } + + if baseDir != "" { + header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source)) + } + + if info.IsDir() { + header.Name += "/" + } else { + header.Method = zip.Deflate + } + + writer, err := archive.CreateHeader(header) + if err != nil { + return err + } + + if info.IsDir() { + return nil + } + + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + _, err = io.Copy(writer, file) + return err + }) + + archive.Close() + + return err +}