all repos — nds-converter @ main

A lightweight save converter for NDS and DeSmuME.

nds-converter.go (view raw)

  1package main
  2
  3import (
  4	_ "embed"
  5	"net/http"
  6	"os"
  7	"strconv"
  8
  9	"github.com/joho/godotenv"
 10)
 11
 12const (
 13	MB                 = 1 << 20
 14	DefaultmaxFileSize = 2
 15	DefaultPort        = "1111"
 16)
 17
 18var (
 19	//go:embed index.html
 20	indexPage     []byte
 21	maxFileSize   int64
 22	maxFileSizeMB int64
 23)
 24
 25func main() {
 26	// Load the .env file
 27	err := godotenv.Load()
 28	if err != nil {
 29		println("Could not load .env file")
 30	}
 31
 32	port := os.Getenv("PORT")
 33	if port == "" {
 34		port = DefaultPort
 35	}
 36
 37	fileSizeString := os.Getenv("MAX_SIZE_MB")
 38	maxFileSize, err = strconv.ParseInt(fileSizeString, 10, 64)
 39	if err != nil {
 40		maxFileSize = DefaultmaxFileSize
 41	}
 42	println("Max file size:", maxFileSize, "MB.")
 43	maxFileSizeMB = maxFileSize * MB
 44
 45	http.HandleFunc("/", mainHandler)
 46	println("Listening on port " + port)
 47	http.ListenAndServe(":"+port, nil)
 48}
 49
 50func mainHandler(w http.ResponseWriter, r *http.Request) {
 51	switch r.Method {
 52	case http.MethodGet:
 53		getHandler(w)
 54		return
 55	case http.MethodPost:
 56		postHandler(w, r)
 57	default:
 58		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
 59	}
 60}
 61
 62func getHandler(w http.ResponseWriter) {
 63	w.Write(indexPage)
 64}
 65
 66func postHandler(w http.ResponseWriter, r *http.Request) {
 67	// Parse the multipart form data
 68	err := r.ParseMultipartForm(maxFileSizeMB)
 69	if err != nil {
 70		http.Error(w, "Error parsing form", http.StatusBadRequest)
 71		return
 72	}
 73
 74	// Limit upload file size
 75	r.Body = http.MaxBytesReader(w, r.Body, maxFileSizeMB)
 76
 77	// Get the file from the request
 78	file, h, err := r.FormFile("file")
 79	if err != nil {
 80		http.Error(w, "Error retrieving file from form data", http.StatusBadRequest)
 81		return
 82	}
 83	defer file.Close()
 84
 85	// Check file size
 86	if h.Size > maxFileSizeMB {
 87		http.Error(w, "File size exceeds "+strconv.FormatInt(maxFileSize, 10)+"MB", http.StatusBadRequest)
 88		return
 89	}
 90
 91	// Convert file
 92	output, err := Convert(file, h)
 93	if err != nil {
 94		http.Error(w, err.Error(), http.StatusInternalServerError)
 95		return
 96	}
 97
 98	// Send response
 99	w.Write(output)
100}