util.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. // Copyright (c) 2015-2019 Jeevanandam M (jeeva@myjeeva.com), All rights reserved.
  2. // resty source code and usage is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package resty
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "encoding/xml"
  9. "fmt"
  10. "io"
  11. "log"
  12. "mime/multipart"
  13. "net/http"
  14. "net/textproto"
  15. "os"
  16. "path/filepath"
  17. "reflect"
  18. "runtime"
  19. "sort"
  20. "strings"
  21. )
  22. //‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
  23. // Package Helper methods
  24. //___________________________________
  25. // IsStringEmpty method tells whether given string is empty or not
  26. func IsStringEmpty(str string) bool {
  27. return len(strings.TrimSpace(str)) == 0
  28. }
  29. // DetectContentType method is used to figure out `Request.Body` content type for request header
  30. func DetectContentType(body interface{}) string {
  31. contentType := plainTextType
  32. kind := kindOf(body)
  33. switch kind {
  34. case reflect.Struct, reflect.Map:
  35. contentType = jsonContentType
  36. case reflect.String:
  37. contentType = plainTextType
  38. default:
  39. if b, ok := body.([]byte); ok {
  40. contentType = http.DetectContentType(b)
  41. } else if kind == reflect.Slice {
  42. contentType = jsonContentType
  43. }
  44. }
  45. return contentType
  46. }
  47. // IsJSONType method is to check JSON content type or not
  48. func IsJSONType(ct string) bool {
  49. return jsonCheck.MatchString(ct)
  50. }
  51. // IsXMLType method is to check XML content type or not
  52. func IsXMLType(ct string) bool {
  53. return xmlCheck.MatchString(ct)
  54. }
  55. // Unmarshal content into object from JSON or XML
  56. // Deprecated: kept for backward compatibility
  57. func Unmarshal(ct string, b []byte, d interface{}) (err error) {
  58. if IsJSONType(ct) {
  59. err = json.Unmarshal(b, d)
  60. } else if IsXMLType(ct) {
  61. err = xml.Unmarshal(b, d)
  62. }
  63. return
  64. }
  65. // Unmarshalc content into object from JSON or XML
  66. func Unmarshalc(c *Client, ct string, b []byte, d interface{}) (err error) {
  67. if IsJSONType(ct) {
  68. err = c.JSONUnmarshal(b, d)
  69. } else if IsXMLType(ct) {
  70. err = xml.Unmarshal(b, d)
  71. }
  72. return
  73. }
  74. //‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
  75. // RequestLog and ResponseLog type
  76. //___________________________________
  77. // RequestLog struct is used to collected information from resty request
  78. // instance for debug logging. It sent to request log callback before resty
  79. // actually logs the information.
  80. type RequestLog struct {
  81. Header http.Header
  82. Body string
  83. }
  84. // ResponseLog struct is used to collected information from resty response
  85. // instance for debug logging. It sent to response log callback before resty
  86. // actually logs the information.
  87. type ResponseLog struct {
  88. Header http.Header
  89. Body string
  90. }
  91. //‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
  92. // Package Unexported methods
  93. //___________________________________
  94. // way to disable the HTML escape as opt-in
  95. func jsonMarshal(c *Client, r *Request, d interface{}) ([]byte, error) {
  96. if !r.jsonEscapeHTML {
  97. return noescapeJSONMarshal(d)
  98. } else if !c.jsonEscapeHTML {
  99. return noescapeJSONMarshal(d)
  100. }
  101. return c.JSONMarshal(d)
  102. }
  103. func firstNonEmpty(v ...string) string {
  104. for _, s := range v {
  105. if !IsStringEmpty(s) {
  106. return s
  107. }
  108. }
  109. return ""
  110. }
  111. func getLogger(w io.Writer) *log.Logger {
  112. return log.New(w, "RESTY ", log.LstdFlags)
  113. }
  114. var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
  115. func escapeQuotes(s string) string {
  116. return quoteEscaper.Replace(s)
  117. }
  118. func createMultipartHeader(param, fileName, contentType string) textproto.MIMEHeader {
  119. hdr := make(textproto.MIMEHeader)
  120. hdr.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
  121. escapeQuotes(param), escapeQuotes(fileName)))
  122. hdr.Set("Content-Type", contentType)
  123. return hdr
  124. }
  125. func addMultipartFormField(w *multipart.Writer, mf *MultipartField) error {
  126. partWriter, err := w.CreatePart(createMultipartHeader(mf.Param, mf.FileName, mf.ContentType))
  127. if err != nil {
  128. return err
  129. }
  130. _, err = io.Copy(partWriter, mf.Reader)
  131. return err
  132. }
  133. func writeMultipartFormFile(w *multipart.Writer, fieldName, fileName string, r io.Reader) error {
  134. // Auto detect actual multipart content type
  135. cbuf := make([]byte, 512)
  136. size, err := r.Read(cbuf)
  137. if err != nil {
  138. return err
  139. }
  140. partWriter, err := w.CreatePart(createMultipartHeader(fieldName, fileName, http.DetectContentType(cbuf)))
  141. if err != nil {
  142. return err
  143. }
  144. if _, err = partWriter.Write(cbuf[:size]); err != nil {
  145. return err
  146. }
  147. _, err = io.Copy(partWriter, r)
  148. return err
  149. }
  150. func addFile(w *multipart.Writer, fieldName, path string) error {
  151. file, err := os.Open(path)
  152. if err != nil {
  153. return err
  154. }
  155. defer closeq(file)
  156. return writeMultipartFormFile(w, fieldName, filepath.Base(path), file)
  157. }
  158. func addFileReader(w *multipart.Writer, f *File) error {
  159. return writeMultipartFormFile(w, f.ParamName, f.Name, f.Reader)
  160. }
  161. func getPointer(v interface{}) interface{} {
  162. vv := valueOf(v)
  163. if vv.Kind() == reflect.Ptr {
  164. return v
  165. }
  166. return reflect.New(vv.Type()).Interface()
  167. }
  168. func isPayloadSupported(m string, allowMethodGet bool) bool {
  169. return !(m == MethodHead || m == MethodOptions || (m == MethodGet && !allowMethodGet))
  170. }
  171. func typeOf(i interface{}) reflect.Type {
  172. return indirect(valueOf(i)).Type()
  173. }
  174. func valueOf(i interface{}) reflect.Value {
  175. return reflect.ValueOf(i)
  176. }
  177. func indirect(v reflect.Value) reflect.Value {
  178. return reflect.Indirect(v)
  179. }
  180. func kindOf(v interface{}) reflect.Kind {
  181. return typeOf(v).Kind()
  182. }
  183. func createDirectory(dir string) (err error) {
  184. if _, err = os.Stat(dir); err != nil {
  185. if os.IsNotExist(err) {
  186. if err = os.MkdirAll(dir, 0755); err != nil {
  187. return
  188. }
  189. }
  190. }
  191. return
  192. }
  193. func canJSONMarshal(contentType string, kind reflect.Kind) bool {
  194. return IsJSONType(contentType) && (kind == reflect.Struct || kind == reflect.Map || kind == reflect.Slice)
  195. }
  196. func functionName(i interface{}) string {
  197. return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
  198. }
  199. func acquireBuffer() *bytes.Buffer {
  200. return bufPool.Get().(*bytes.Buffer)
  201. }
  202. func releaseBuffer(buf *bytes.Buffer) {
  203. if buf != nil {
  204. buf.Reset()
  205. bufPool.Put(buf)
  206. }
  207. }
  208. func closeq(v interface{}) {
  209. if c, ok := v.(io.Closer); ok {
  210. sliently(c.Close())
  211. }
  212. }
  213. func sliently(_ ...interface{}) {}
  214. func composeHeaders(hdrs http.Header) string {
  215. var str []string
  216. for _, k := range sortHeaderKeys(hdrs) {
  217. str = append(str, fmt.Sprintf("%25s: %s", k, strings.Join(hdrs[k], ", ")))
  218. }
  219. return strings.Join(str, "\n")
  220. }
  221. func sortHeaderKeys(hdrs http.Header) []string {
  222. var keys []string
  223. for key := range hdrs {
  224. keys = append(keys, key)
  225. }
  226. sort.Strings(keys)
  227. return keys
  228. }
  229. func copyHeaders(hdrs http.Header) http.Header {
  230. nh := http.Header{}
  231. for k, v := range hdrs {
  232. nh[k] = v
  233. }
  234. return nh
  235. }