golang-lib/web/request.go

71 lines
1.6 KiB
Go
Raw Normal View History

2021-06-01 10:51:35 +02:00
package web
2019-08-07 00:15:50 +02:00
import (
2021-07-21 15:35:22 +02:00
"bytes"
2019-08-07 00:15:50 +02:00
"encoding/json"
2021-07-21 15:35:22 +02:00
"io"
"mime/multipart"
2019-08-07 00:15:50 +02:00
"net/http"
2021-07-21 15:35:22 +02:00
"os"
"path/filepath"
2019-08-07 00:15:50 +02:00
"time"
)
2021-07-19 17:59:47 +02:00
// JSONRequest issues a GET request to the specified URL and reads the returned
// JSON into value. See json.Unmarshal for the rules for converting JSON into a
// value.
2019-08-07 00:15:50 +02:00
func JSONRequest(url string, value interface{}) error {
2021-07-19 17:59:47 +02:00
netClient := &http.Client{
2019-08-07 00:15:50 +02:00
Timeout: time.Second * 20,
}
resp, err := netClient.Get(url)
if err != nil {
return err
}
err = json.NewDecoder(resp.Body).Decode(&value)
2021-07-19 17:59:47 +02:00
resp.Body.Close()
2019-08-07 00:15:50 +02:00
if err != nil {
return err
}
return nil
}
2021-07-21 15:35:22 +02:00
// NewRequestWithFile Create a Request with file as body
func NewRequestWithFile(url, filename string) (*http.Request, error) {
buf := bytes.NewBuffer(nil)
bodyWriter := multipart.NewWriter(buf)
// We need to truncate the input filename, as the server might be stupid and take the input
// filename verbatim. Then, he will have directory parts which do not exist on the server.
fileWriter, err := bodyWriter.CreateFormFile("file", filepath.Base(filename))
if err != nil {
return nil, err
}
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
if _, err := io.Copy(fileWriter, file); err != nil {
return nil, err
}
// We have all the data written to the bodyWriter.
// Now we can infer the content type
contentType := bodyWriter.FormDataContentType()
// This is mandatory as it flushes the buffer.
bodyWriter.Close()
req, err := http.NewRequest(http.MethodPost, url, buf)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", contentType)
return req, nil
}