Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
golang upload client and server
// curl -X POST -H "Content-Type: application/octet-stream" --data-binary '@filename'
package main
import (
func uploadHandler(w http.ResponseWriter, r *http.Request) {
file, err := os.Create("./result")
if err != nil {
n, err := io.Copy(file, r.Body)
if err != nil {
w.Write([]byte(fmt.Sprintf("%d bytes are recieved.\n", n)))
func main() {
http.HandleFunc("/upload", uploadHandler)
go func() {
time.Sleep(time.Second * 1)
http.ListenAndServe(":5050", nil)
func upload() {
file, err := os.Open("./filename")
if err != nil {
defer file.Close()
res, err := http.Post("", "binary/octet-stream", file)
if err != nil {
defer res.Body.Close()
message, _ := ioutil.ReadAll(res.Body)
Copy link

wingyplus commented Mar 7, 2018

Copy link

Keithwachira commented Jul 8, 2018

Thank you for this it helped me in writing my go file upload handler

Copy link

Henry75m39 commented Jun 25, 2019

I'm gonna to try it.

Copy link

robertranjan commented Oct 16, 2020

@ebraminio, this code works well. Good job!
Quick question:
what are you doing with the anonymous go routine at line# 30 - 33 & the func upload()? Are they necessary?
Program works even if I commented them. Shall we safely ignore them?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment