abyss/main.go

64 lines
1.3 KiB
Go
Raw Normal View History

2024-08-19 12:48:30 -03:00
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"time"
)
const (
port = ":8080"
2024-08-19 13:54:33 -03:00
filesDir = "./files"
2024-08-19 12:48:30 -03:00
)
2024-08-19 15:50:17 -03:00
var url string = os.Getenv("URL")
2024-08-19 12:48:30 -03:00
func main() {
http.HandleFunc("/upload", uploadHandler)
2024-08-19 13:54:33 -03:00
http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir(filesDir))))
2024-08-19 12:48:30 -03:00
log.Printf("Server running on port %s\n", port)
log.Fatal(http.ListenAndServe(port, nil))
}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
return
}
2024-08-19 13:54:33 -03:00
file, _, err := r.FormFile("file")
2024-08-19 12:48:30 -03:00
if err != nil {
http.Error(w, "Error retrieving the file", http.StatusBadRequest)
return
}
defer file.Close()
2024-08-19 13:54:33 -03:00
if _, err := os.Stat(filesDir); err != nil {
if err := os.Mkdir(filesDir, 0750); err != nil {
http.Error(w, "Error creating storage directory", http.StatusInternalServerError)
2024-08-19 12:48:30 -03:00
}
}
2024-08-19 13:54:33 -03:00
time := int64(float64(time.Now().Unix()) * 2.71828) // euler :)
filename := fmt.Sprintf("%s/%d", filesDir, time)
2024-08-19 12:48:30 -03:00
dst, err := os.Create(filename)
if err != nil {
2024-08-19 13:54:33 -03:00
http.Error(w, "Error creating file\n", http.StatusInternalServerError)
2024-08-19 12:48:30 -03:00
}
defer dst.Close()
if _, err := io.Copy(dst, file); err != nil {
http.Error(w, "Error copying the file", http.StatusInternalServerError)
}
2024-08-19 15:50:17 -03:00
if url == "" {
fmt.Fprintf(w, "http://localhost%s/%d\n", port, time)
} else {
fmt.Fprintf(w, "http://%s/%d\n", url, time)
}
2024-08-19 12:48:30 -03:00
}