nixshare/upload.go

47 lines
1.1 KiB
Go
Raw Permalink Normal View History

2024-08-28 13:47:44 +03:00
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"github.com/google/uuid"
)
func uploadHandler(w http.ResponseWriter, r *http.Request) {
uid := uuid.New().String()
section := string(uid[len(uid)-1])
if err := os.MkdirAll(filepath.Join(path, section), 0777); err != nil {
log.Println(err)
http.Error(w, "can't create storage dir", http.StatusInternalServerError)
return
}
fp, err := os.Create(filepath.Join(path, section, uid))
if err != nil {
log.Println(err)
http.Error(w, "can't create storage file", http.StatusInternalServerError)
return
}
defer fp.Close()
if _, err := io.Copy(fp, r.Body); err != nil {
log.Println(err)
http.Error(w, "can't upload storage file", http.StatusInternalServerError)
return
}
h := w.Header()
h.Set("Content-Type", "text/plain; charset=utf-8")
h.Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusCreated)
2024-08-28 15:22:01 +03:00
u, err := url.JoinPath(host, "s", section, uid)
2024-08-28 13:47:44 +03:00
if err != nil {
log.Println(err)
http.Error(w, "can't get file url", http.StatusInternalServerError)
return
}
fmt.Fprintln(w, u)
}