70 lines
1.4 KiB
Go
70 lines
1.4 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", "See go.balki.me/anyhttp for usage")
|
|
dumpFile := flag.String("dumpfile", "dump.json", "local storage file path")
|
|
|
|
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) {
|
|
|
|
if _, err := w.Write([]byte("OK")); err != nil {
|
|
log.Panic(err)
|
|
}
|
|
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!")
|
|
})
|
|
|
|
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 {
|
|
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)
|
|
}
|
|
}
|