56 lines
1.0 KiB
Go
56 lines
1.0 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"html/template"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
func handle(path string, handleFunc func(res http.ResponseWriter, req *http.Request) error) {
|
|
http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
|
|
err := handleFunc(res, req)
|
|
if err != nil {
|
|
log.Println(err)
|
|
http.Error(res, err.Error(), 500)
|
|
}
|
|
})
|
|
}
|
|
|
|
func handleForm(res http.ResponseWriter, req *http.Request) error {
|
|
tpl, err := template.ParseFiles("form.html")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var msg string
|
|
if req.Method == http.MethodPost {
|
|
file, header, err := req.FormFile("file")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer file.Close()
|
|
|
|
tmpFile, err := os.Create(filepath.Join(os.TempDir(), header.Filename))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tmpFile.Close()
|
|
|
|
sz, err := io.Copy(tmpFile, file)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
msg = fmt.Sprintf("File uploaded (%d bytes)", sz)
|
|
}
|
|
tpl.Execute(res, msg)
|
|
return nil
|
|
}
|
|
|
|
func main() {
|
|
handle("/", handleForm)
|
|
http.ListenAndServe(":9000", nil)
|
|
}
|