HTTP File Upload and Download Implementation
This Go HTTP server handles file uploads and serves files for download:
package main
import (
"crypto/rand"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
)
const (
uploadDir = "storage"
maxSize = 10 << 20 // 10MB
)
func main() {
http.HandleFunc("/upload", uploadHandler)
http.Handle("/static/", http.StripPrefix("/static/",
http.FileServer(http.Dir(uploadDir))))
http.ListenAndServe(":8888", nil)
}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(maxSize)
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, "Invalid file", http.StatusBadRequest)
return
}
defer file.Close()
if header.Size > maxSize {
http.Error(w, "File too large", http.StatusRequestEntityTooLarge)
return
}
fileBytes, err := io.ReadAll(file)
if err != nil {
http.Error(w, "Read error", http.StatusInternalServerError)
return
}
uniqueName := generateID(12) + filepath.Ext(header.Filename)
filePath := filepath.Join(uploadDir, uniqueName)
if err := os.WriteFile(filePath, fileBytes, 0666); err != nil {
http.Error(w, "Save failed", http.StatusInternalServerError)
return
}
w.Write([]byte("Upload successful"))
}
func generateID(length int) string {
b := make([]byte, length)
rand.Read(b)
return fmt.Sprintf("%x", b)
}
Cross-Platform Browser Launching
This implementation opens URLs in the default browser across different operating systems:
package main
import (
"os/exec"
"runtime"
)
func main() {
openBrowser("http://localhost:8889")
}
func openBrowser(url string) error {
var cmd string
var args []string
switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start", url}
case "darwin":
cmd = "open"
args = []string{url}
default: // Linux and BSD
cmd = "xdg-open"
args = []string{url}
}
return exec.Command(cmd, args...).Start()
}