Created
October 29, 2020 04:09
-
-
Save joshcarp/e1494847c372a28f2bc9dceb0f06e89d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package website_from_gcs | |
import ( | |
"archive/zip" | |
"github.com/joshcarp/gop" | |
gop3 "github.com/joshcarp/gop/gop" | |
"github.com/joshcarp/gop/gop/gop_gcs" | |
"github.com/spf13/afero" | |
"github.com/spf13/afero/zipfs" | |
"mime" | |
"net/http" | |
"os" | |
"path" | |
"strings" | |
) | |
func ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
var err error | |
retr := gop_gcs.New(os.Getenv("BUCKET")) | |
defer func() { | |
gop.HandleErr(w, err) | |
}() | |
switch r.Method { | |
case "GET": | |
err = GET(retr, w, r) | |
case "POST": | |
err = POST(retr, w, r) | |
} | |
} | |
func POST(retr gop3.Cacher, w http.ResponseWriter, r *http.Request)error { | |
f, h, err := r.FormFile("content") | |
if err != nil{ | |
return err | |
} | |
b, err := zip.NewReader(f, h.Size) | |
if err != nil{ | |
return err | |
} | |
fs := zipfs.New(b) | |
err = readFileFromFs(fs,retr, r.FormValue("name")) | |
if err != nil{ | |
return err | |
} | |
return nil | |
} | |
func GET(retr gop3.Retriever, w http.ResponseWriter, r *http.Request) error{ | |
pth := strings.TrimLeft(r.URL.Path, "/") | |
pth = strings.TrimLeft(pth, os.Getenv("BASE_PATH")) | |
pth = strings.TrimRight(pth, "/") | |
pth = path.Join(os.Getenv("BASE"), pth) | |
switch path.Ext(pth) { | |
case "": | |
pth += "/index.html" | |
} | |
w.Header().Add("Content-Type", mime.TypeByExtension(path.Ext(pth))) | |
res, _, err := retr.Retrieve(pth) | |
if err != nil { | |
return nil | |
} | |
_, err = w.Write(res) | |
return err | |
} | |
func readFileFromFs(fs afero.Fs, cacher gop3.Cacher, base string) error { | |
return afero.Walk(fs, "/", func(pth string, info os.FileInfo, err error) error { | |
if info != nil && !info.IsDir() { | |
f, _ := afero.ReadFile(fs, pth) | |
err = cacher.Cache(path.Join(base, pth), f) | |
} | |
return err | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment