Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto detect Multipart content type #118

Merged
merged 2 commits into from
Jan 24, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 32 additions & 11 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"net/textproto"
"os"
"path/filepath"
"reflect"
Expand Down Expand Up @@ -98,32 +100,51 @@ func getLogger(w io.Writer) *log.Logger {
return log.New(w, "RESTY ", log.LstdFlags)
}

func addFile(w *multipart.Writer, fieldName, path string) error {
file, err := os.Open(path)
var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")

func escapeQuotes(s string) string {
return quoteEscaper.Replace(s)
}

func writeMultipartFormFile(w *multipart.Writer, fieldName, fileName string, r io.Reader) error {
// Auto detect actual multipart content type
cbuf := make([]byte, 512)
size, err := r.Read(cbuf)
if err != nil {
return err
}
defer func() {
_ = file.Close()
}()

part, err := w.CreateFormFile(fieldName, filepath.Base(path))
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
escapeQuotes(fieldName), escapeQuotes(fileName)))
h.Set("Content-Type", http.DetectContentType(cbuf))
partWriter, err := w.CreatePart(h)
if err != nil {
return err
}
_, err = io.Copy(part, file)

if _, err = partWriter.Write(cbuf[:size]); err != nil {
return err
}

_, err = io.Copy(partWriter, r)
return err
}

func addFileReader(w *multipart.Writer, f *File) error {
part, err := w.CreateFormFile(f.ParamName, f.Name)
func addFile(w *multipart.Writer, fieldName, path string) error {
file, err := os.Open(path)
if err != nil {
return err
}
_, err = io.Copy(part, f.Reader)
defer func() {
_ = file.Close()
}()

return err
return writeMultipartFormFile(w, fieldName, filepath.Base(path), file)
}

func addFileReader(w *multipart.Writer, f *File) error {
return writeMultipartFormFile(w, f.ParamName, f.Name, f.Reader)
}

func getPointer(v interface{}) interface{} {
Expand Down