Skip to content

Commit

Permalink
code improvements, preparing for v1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
jeevatkm committed Sep 19, 2017
1 parent 41c7684 commit f8e1383
Show file tree
Hide file tree
Showing 4 changed files with 178 additions and 170 deletions.
164 changes: 0 additions & 164 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,15 @@ import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"runtime"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -649,13 +643,7 @@ func (c *Client) SetRootCertificate(pemFilePath string) *Client {
// resty.SetOutputDirectory("/save/http/response/here")
//
func (c *Client) SetOutputDirectory(dirPath string) *Client {
err := createDirectory(dirPath)
if err != nil {
c.Log.Printf("ERROR [%v]", err)
}

c.outputDirectory = dirPath

return c
}

Expand Down Expand Up @@ -834,155 +822,3 @@ type File struct {
func (f *File) String() string {
return fmt.Sprintf("ParamName: %v; FileName: %v", f.ParamName, f.Name)
}

//
// Helper methods
//

// IsStringEmpty method tells whether given string is empty or not
func IsStringEmpty(str string) bool {
return (len(strings.TrimSpace(str)) == 0)
}

// DetectContentType method is used to figure out `Request.Body` content type for request header
func DetectContentType(body interface{}) string {
contentType := plainTextType
kind := kindOf(body)
switch kind {
case reflect.Struct, reflect.Map:
contentType = jsonContentType
case reflect.String:
contentType = plainTextType
default:
if b, ok := body.([]byte); ok {
contentType = http.DetectContentType(b)
} else if kind == reflect.Slice {
contentType = jsonContentType
}
}

return contentType
}

// IsJSONType method is to check JSON content type or not
func IsJSONType(ct string) bool {
return jsonCheck.MatchString(ct)
}

// IsXMLType method is to check XML content type or not
func IsXMLType(ct string) bool {
return xmlCheck.MatchString(ct)
}

// Unmarshal content into object from JSON or XML
// Deprecated: kept for backward compatibility
func Unmarshal(ct string, b []byte, d interface{}) (err error) {
if IsJSONType(ct) {
err = json.Unmarshal(b, d)
} else if IsXMLType(ct) {
err = xml.Unmarshal(b, d)
}

return
}

// Unmarshalc content into object from JSON or XML
func Unmarshalc(c *Client, ct string, b []byte, d interface{}) (err error) {
if IsJSONType(ct) {
err = c.JSONUnmarshal(b, d)
} else if IsXMLType(ct) {
err = xml.Unmarshal(b, d)
}

return
}

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)
if err != nil {
return err
}
defer func() {
_ = file.Close()
}()

part, err := w.CreateFormFile(fieldName, filepath.Base(path))
if err != nil {
return err
}
_, err = io.Copy(part, file)

return err
}

func addFileReader(w *multipart.Writer, f *File) error {
part, err := w.CreateFormFile(f.ParamName, f.Name)
if err != nil {
return err
}
_, err = io.Copy(part, f.Reader)

return err
}

func getPointer(v interface{}) interface{} {
vv := valueOf(v)
if vv.Kind() == reflect.Ptr {
return v
}
return reflect.New(vv.Type()).Interface()
}

func isPayloadSupported(m string, allowMethodGet bool) bool {
return (m == MethodPost || m == MethodPut || m == MethodDelete || m == MethodPatch || (allowMethodGet && m == MethodGet))
}

func typeOf(i interface{}) reflect.Type {
return indirect(valueOf(i)).Type()
}

func valueOf(i interface{}) reflect.Value {
return reflect.ValueOf(i)
}

func indirect(v reflect.Value) reflect.Value {
return reflect.Indirect(v)
}

func kindOf(v interface{}) reflect.Kind {
return typeOf(v).Kind()
}

func createDirectory(dir string) (err error) {
if _, err = os.Stat(dir); err != nil {
if os.IsNotExist(err) {
if err = os.MkdirAll(dir, 0755); err != nil {
return
}
}
}
return
}

func canJSONMarshal(contentType string, kind reflect.Kind) bool {
return IsJSONType(contentType) && (kind == reflect.Struct || kind == reflect.Map)
}

func functionName(i interface{}) string {
return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
}

func acquireBuffer() *bytes.Buffer {
return bufPool.Get().(*bytes.Buffer)
}

func releaseBuffer(buf *bytes.Buffer) {
if buf != nil {
buf.Reset()
bufPool.Put(buf)
}
}
11 changes: 6 additions & 5 deletions middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,12 @@ import (
"path/filepath"
"reflect"
"strings"
"time"
)

//
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Request Middleware(s)
//
//___________________________________

func parseRequestURL(c *Client, r *Request) error {
// Parsing request URL
Expand Down Expand Up @@ -70,10 +71,10 @@ func parseRequestURL(c *Client, r *Request) error {
func parseRequestHeader(c *Client, r *Request) error {
hdr := http.Header{}
for k := range c.Header {
hdr.Set(k, c.Header.Get(k))
hdr[k] = append(hdr[k], c.Header[k]...)
}
for k := range r.Header {
hdr.Set(k, r.Header.Get(k))
hdr[k] = append(hdr[k], r.Header[k]...)
}

if IsStringEmpty(hdr.Get(hdrUserAgentKey)) {
Expand Down Expand Up @@ -217,7 +218,7 @@ func responseLogger(c *Client, res *Response) error {
c.disableLogPrefix()
c.Log.Println("---------------------- RESPONSE LOG -----------------------")
c.Log.Printf("STATUS : %s", res.Status())
c.Log.Printf("RECEIVED AT : %v", res.ReceivedAt())
c.Log.Printf("RECEIVED AT : %v", res.ReceivedAt().Format(time.RFC3339Nano))
c.Log.Printf("RESPONSE TIME : %v", res.Time())
c.Log.Println("HEADERS:")
for h, v := range res.Header() {
Expand Down
2 changes: 1 addition & 1 deletion request.go
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ func (r *Request) Execute(method, url string) (*Response, error) {
}

//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Unexported methods
// Request Unexported methods
//___________________________________

func (r *Request) fmtBodyString() (body string) {
Expand Down
Loading

0 comments on commit f8e1383

Please sign in to comment.