awesome-patterns/playground/http/upload_test.go

64 lines
1.3 KiB
Go
Raw Normal View History

2018-09-19 09:52:44 +03:00
package http
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"path/filepath"
"testing"
)
func TestUploadFormFile(t *testing.T) {
var filePath = "/Users/bruce/Desktop/HVAC-CoolMasterNet.yml"
var url = "http://localhost:48081/api/v1/deviceprofile/uploadfile"
2018-09-19 10:19:35 +03:00
// Retch file
fmt.Println("Read file: ", filepath.Base(filePath))
yamlFile, err := ioutil.ReadFile(filePath)
2018-09-19 09:52:44 +03:00
if err != nil {
t.Fatal(err)
}
// create form data
2018-09-19 10:43:22 +03:00
body := new(bytes.Buffer)
//body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
2018-09-19 10:47:46 +03:00
formFileWriter, err := writer.CreateFormFile("file", filepath.Base(filePath))
2018-09-19 09:52:44 +03:00
if err != nil {
t.Fatal(err)
}
2018-09-24 04:12:35 +03:00
_, err = io.Copy(formFileWriter, bytes.NewReader(yamlFile))
if err != nil {
2018-09-19 09:52:44 +03:00
t.Fatal(err)
}
writer.Close()
// create http post request
2018-09-19 10:43:22 +03:00
req, err := http.NewRequest(http.MethodPost, url, body)
2018-09-19 09:52:44 +03:00
if err != nil {
t.Fatal(err)
}
req.Header.Add("Content-Type", writer.FormDataContentType())
// submit request
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
// check response
fmt.Println("== upload finish ==")
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
fmt.Println(res.StatusCode)
fmt.Println(res.Header)
res.Body.Close()
fmt.Println(string(resBody))
}