Skip to content

Instantly share code, notes, and snippets.

@hustlijian
Created December 28, 2018 14:05
Show Gist options
  • Save hustlijian/45e5f31af147992fb77a54d925e92659 to your computer and use it in GitHub Desktop.
Save hustlijian/45e5f31af147992fb77a54d925e92659 to your computer and use it in GitHub Desktop.
// curl -X POST -H "Content-Type: application/octet-stream" --data-binary '@filename' http://127.0.0.1:5050/upload
// curl -F "uploadfile=@test.txt" http://127.0.0.1:5050/upload2
// go run main.go
package main
import (
"fmt"
"io"
"net/http"
"os"
"time"
"io/ioutil"
)
func uploadHandler(w http.ResponseWriter, r *http.Request) {
file, err := os.Create("./result")
if err != nil {
panic(err)
}
n, err := io.Copy(file, r.Body)
if err != nil {
panic(err)
}
w.Write([]byte(fmt.Sprintf("%d bytes are recieved.\n", n)))
}
func uploadHandler2(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(32 << 20)
file, handler, err := r.FormFile("uploadfile")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
fmt.Fprintf(w, "%v", handler.Header)
f, err := os.OpenFile("./"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
n, err := io.Copy(f, file)
w.Write([]byte(fmt.Sprintf("%d bytes are recieved.\n", n)))
}
func main() {
http.HandleFunc("/upload", uploadHandler)
http.HandleFunc("/upload2", uploadHandler2)
go func() {
time.Sleep(time.Second * 1)
upload()
}()
http.ListenAndServe(":5050", nil)
}
func upload() {
file, err := os.Open("./filename")
if err != nil {
panic(err)
}
defer file.Close()
res, err := http.Post("http://127.0.0.1:5050/upload", "binary/octet-stream", file)
if err != nil {
panic(err)
}
defer res.Body.Close()
message, _ := ioutil.ReadAll(res.Body)
fmt.Printf(string(message))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment