Skip to content

Instantly share code, notes, and snippets.

@chlp
Last active April 4, 2019 13:10
Show Gist options
  • Save chlp/2cd5d72ac611eeb9c037a9da4ae9e596 to your computer and use it in GitHub Desktop.
Save chlp/2cd5d72ac611eeb9c037a9da4ae9e596 to your computer and use it in GitHub Desktop.
go webserver with file uploading
// chlp 2019
// go run server.go
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"os"
"strconv"
)
func handler(w http.ResponseWriter, r *http.Request) {
var Buf bytes.Buffer
file, header, err := r.FormFile("file")
var fileName = ""
if err == nil {
defer file.Close()
fileName = header.Filename
file2, err := os.Create("./" + fileName)
if err != nil {
panic(err)
}
_, err2 := io.Copy(file2, file)
if err2 != nil {
panic(err)
}
Buf.Reset()
}
fmt.Fprintf(w, `<html><body><form action="/" method="POST" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit">
</form><br>
`)
if len(fileName) > 0 {
fmt.Fprintf(w, fileName)
fmt.Printf(fileName + "\r\n")
}
fmt.Fprintf(w, `</html></body>`)
}
func main() {
http.HandleFunc("/", handler)
var port = 5050
fmt.Printf("Open in your browser http://127.0.0.1:" + strconv.Itoa(port) + "\r\n")
http.ListenAndServe(":"+strconv.Itoa(port), nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment