Last active
March 22, 2023 06:01
-
-
Save ebraminio/576fdfdff425bf3335b51a191a65dbdb to your computer and use it in GitHub Desktop.
golang upload client and server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// curl -X POST -H "Content-Type: application/octet-stream" --data-binary '@filename' http://127.0.0.1:5050/upload | |
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 main() { | |
http.HandleFunc("/upload", uploadHandler) | |
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)) | |
} |
Thank you for this it helped me in writing my go file upload handler
I'm gonna to try it.
@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?
Sorry for the very late, probably will be useful for others at least,
Are they necessary?
No, it's only for testing
Shall we safely ignore them?
Sure.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/ebraminio/576fdfdff425bf3335b51a191a65dbdb#file-upload-go-L15
file
ไม่ได้ Close นะครับ