remote-local-storage/main.go

74 lines
1.5 KiB
Go

// Save and serve HTML local storage in server
package main
import (
"bytes"
_ "embed"
"flag"
"io"
"log"
"net/http"
"os"
"time"
"go.balki.me/anyhttp"
)
//go:embed wrap.html
var html []byte
func main() {
addr := flag.String("address", "localhost:3242", "Listen address. See go.balki.me/anyhttp for usage")
dumpFile := flag.String("dumpfile", "dump.json", "Path where local storage is saved in server")
flag.Parse()
http.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte("<h2>Error!</h2><p>Check your webserver config, You should not see this!</p>"))
})
http.HandleFunc("/wrap/", func(w http.ResponseWriter, r *http.Request) {
http.ServeContent(w, r, "index.html", time.Now(), bytes.NewReader(html))
})
http.HandleFunc("/wrap/saveLS", func(w http.ResponseWriter, r *http.Request) {
data, err := io.ReadAll(r.Body)
if err != nil {
log.Panic(err)
}
if err := os.WriteFile(*dumpFile, data, 0o400); err != nil {
log.Panic(err)
}
if err != nil {
log.Panic(err)
}
log.Println("Saved!")
if _, err := w.Write([]byte("OK")); err != nil {
log.Panic(err)
}
})
http.HandleFunc("/wrap/loadLS", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
data, err := os.ReadFile(*dumpFile)
if err != nil { // First time
data = []byte("{}")
}
if _, err := w.Write(data); err != nil {
log.Panic(err)
}
log.Println("Sent!")
})
err := anyhttp.ListenAndServe(*addr, nil)
if err != nil {
log.Panic(err)
}
}