2024-08-19 12:48:30 -03:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
2024-08-19 16:11:25 -03:00
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
2024-08-19 12:48:30 -03:00
|
|
|
"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 16:11:25 -03:00
|
|
|
http.Handle("/tree/", http.StripPrefix("/tree", http.FileServer(http.Dir(filesDir))))
|
|
|
|
http.HandleFunc("/", fileHandler)
|
2024-08-19 12:48:30 -03:00
|
|
|
log.Printf("Server running on port %s\n", port)
|
|
|
|
log.Fatal(http.ListenAndServe(port, nil))
|
|
|
|
}
|
|
|
|
|
2024-08-19 16:11:25 -03:00
|
|
|
func fileHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
path := filepath.Join(filesDir, strings.TrimPrefix(r.URL.Path, "/"))
|
|
|
|
|
|
|
|
if fileInfo, err := os.Stat(path); err == nil && !fileInfo.IsDir() {
|
|
|
|
http.ServeFile(w, r, path)
|
|
|
|
} else {
|
|
|
|
http.NotFound(w, r)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-19 12:48:30 -03:00
|
|
|
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
|
|
|
}
|