napping
napping copied to clipboard
Example on how to upload files
Hello,
May I know if there's any example on how to upload files using napping (content-type: multipart/form) ?
Thanks.
Same for me
for the moment I'm doing this like that:
res, _ := napping.Get("https://unsplash.it/250/250?random", nil, nil, nil)
ioutil.WriteFile(path+"image.jpeg", []byte(res.RawText()), 0644)
hope this help
@WnP, I'm doing exactly the same to download files, and it works for me.
I'm using Napping in my rest client for OrientDB, and I'm doing something like this to upload a file:
import (
"bytes"
"net/http"
"net/url"
"strings"
"mime/multipart"
"log"
"io"
"io/ioutil"
"os"
"github.com/jmcvetta/napping"
)
type OSession struct{
*napping.Session
}
func (s *OSession) Upload(r *napping.Request, filename string) error {
r.Method = strings.ToUpper(r.Method)
u, err := url.Parse(r.Url)
if err != nil {
log.Printf("%v", err)
return
}
header := http.Header{}
if s.Header != nil {
for k, _ := range *s.Header {
v := s.Header.Get(k)
header.Set(k, v)
}
}
var req *http.Request
f, _ := os.Open(filename)
buf := &bytes.Buffer{}
w := multipart.NewWriter(buf)
part, err := w.CreateFormFile("Upload", filename)
if err != nil {
log.Printf("FormFile %v", err)
}
_, err = io.Copy(part, f)
err = w.Close()
req, err = http.NewRequest(r.Method, u.String(), buf)
header.Set("Content-Type", w.FormDataContentType())
var userinfo *url.Userinfo
if u.User != nil {
userinfo = u.User
}
if s.Userinfo != nil {
userinfo = s.Userinfo
}
if r.Userinfo != nil {
userinfo = r.Userinfo
}
if r.Header != nil {
for k, v := range *r.Header {
header.Set(k, v[0]) // Is there always guarnateed to be at least one value for a header?
}
}
req.Header = header
//
// Set HTTP Basic authentication if userinfo is supplied
//
if userinfo != nil {
pwd, _ := userinfo.Password()
req.SetBasicAuth(userinfo.Username(), pwd)
if u.Scheme != "https" {
//s.log("WARNING: Using HTTP Basic Auth in cleartext is insecure.")
}
}
//
// Execute the HTTP request
//
var client *http.Client
if s.Client != nil {
client = s.Client
} else {
client = &http.Client{}
s.Client = client
}
resp, err := client.Do(req)
if err != nil {
log.Printf("%v", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("Body: %v", err)
return
}
bod := string(body)
log.Println(bod)
return
}