Golang http POST multipart/form-data (Upload File)

Golang http POST multipart/form-data (Upload File)

Dibawah ini merupakan code untuk melakukan http post menggunakan golang

Golang http POST multipart/form-data (Upload File)


package main

import (
"bytes"

"log"
"mime/multipart"
"net/http"
"os"
"io"
)

func main() {
log.Println("test upload")
body := new(bytes.Buffer)
writer := multipart.NewWriter(body)
filePath := "go.sum"

part, err := writer.CreateFormFile("file", filePath)
if err != nil {
log.Fatal(err)
}

file, err := os.Open(filePath)
if err != nil {
log.Fatal(err)
}

defer file.Close()

_, err = io.Copy(part, file)
if err != nil {
log.Println("err io copy")
}

writer.Close()

req, err := http.NewRequest("POST", "http://localhost:1234/upload-proccess", body)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Content-Type", writer.FormDataContentType())

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal("resp", err)
}
log.Println("resp", resp.StatusCode)

}

Subscribe to receive free email updates:

0 Response to "Golang http POST multipart/form-data (Upload File)"

Post a Comment

1. Berikan Komentar yang Relevan
2. Tidak Mengandung SARA
3. Berkomentar yang Sopan

Konsultasi Aplikasi