summaryrefslogtreecommitdiff
path: root/main.go
diff options
context:
space:
mode:
Diffstat (limited to 'main.go')
-rw-r--r--main.go87
1 files changed, 87 insertions, 0 deletions
diff --git a/main.go b/main.go
new file mode 100644
index 0000000..a542ddb
--- /dev/null
+++ b/main.go
@@ -0,0 +1,87 @@
+package main
+
+import (
+ "crypto/rand"
+ "encoding/base64"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "path/filepath"
+
+ "github.com/robert-nix/ansihtml"
+ flag "github.com/spf13/pflag"
+)
+
+type server struct {
+ data string
+}
+
+func (s *server) Post(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/" {
+ return
+ }
+ var random [16]byte
+ _, err := io.ReadFull(rand.Reader, random[:])
+ if err != nil {
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ filename := base64.RawURLEncoding.EncodeToString(random[:])
+ path := filepath.Join(s.data, filename)
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
+ if err != nil {
+ log.Print("OpenFile(): ", err)
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ defer f.Close()
+ if _, err = io.Copy(f, r.Body); err != nil {
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ w.WriteHeader(http.StatusCreated)
+ fmt.Fprintf(w, "/%s", filename)
+}
+
+func (s *server) Get(w http.ResponseWriter, r *http.Request) {
+ path := r.URL.Path
+ filename := filepath.Join(s.data, path)
+ http.ServeFile(w, r, filename)
+}
+
+func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case "POST":
+ s.Post(w, r)
+ case "GET":
+ s.Get(w, r)
+ }
+}
+
+func main() {
+ var (
+ addr string
+ data string
+ )
+ flag.StringVarP(&addr, "addr", "a", "0.0.0.0:9000", "The address to bind to")
+ flag.StringVarP(&data, "data-path", "d", "./data", "The path to the data")
+ flag.Parse()
+
+ html := ansihtml.ConvertToHTML([]byte("\x1b[33mThis text is yellow.\x1b[m"))
+ // html: `<span style="color:olive;">This text is yellow.</span>`
+ println(string(html))
+
+ datadir, err := filepath.Abs(data)
+ if err != nil {
+ log.Fatal(err)
+ }
+ s := &server{
+ data: datadir,
+ }
+ log.Printf("Listening at '%s'...", addr)
+ if err := http.ListenAndServe(addr, s); err != nil {
+ log.Fatal(err)
+ }
+}