Created
September 10, 2021 10:24
-
-
Save honmaple/60f38d537e3ac6a6501c3da36f9ab81d to your computer and use it in GitHub Desktop.
upload multi file with golang http client
This file contains hidden or 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
package main | |
import ( | |
"bytes" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"mime/multipart" | |
"net/http" | |
"os" | |
"time" | |
) | |
func newFileRequest(uri string, fields map[string]interface{}, files map[string][]string) (*http.Request, error) { | |
body := new(bytes.Buffer) | |
writer := multipart.NewWriter(body) | |
for key, val := range files { | |
for i := range val { | |
fi, err := os.Open(val[i]) | |
if err != nil { | |
return nil, err | |
} | |
defer fi.Close() | |
part, err := writer.CreateFormFile(key, fi.Name()) | |
if err != nil { | |
return nil, err | |
} | |
if _, err := io.Copy(part, fi); err != nil { | |
return nil, err | |
} | |
} | |
} | |
for key, val := range fields { | |
writer.WriteField(key, fmt.Sprintf("%v", val)) | |
} | |
if err := writer.Close(); err != nil { | |
return nil, err | |
} | |
req, err := http.NewRequest("POST", uri, body) | |
if err != nil { | |
return nil, err | |
} | |
req.Header.Add("Content-Type", writer.FormDataContentType()) | |
return req, nil | |
} | |
func main() { | |
fields := map[string]interface{}{ | |
"hostname": "test_host", | |
"timestamp": time.Now().Unix(), | |
} | |
files := map[string][]string{ | |
"file": []string{ | |
"./test.txt", | |
}, | |
} | |
request, err := newFileRequest("http://127.0.0.1:8000/upload", fields, files) | |
if err != nil { | |
panic(err) | |
} | |
client := &http.Client{} | |
resp, err := client.Do(request) | |
if err != nil { | |
panic(err) | |
} | |
defer resp.Body.Close() | |
b, _ := ioutil.ReadAll(resp.Body) | |
fmt.Println(string(b)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment