binding_test.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package binding
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "errors"
  9. "io"
  10. "io/ioutil"
  11. "mime/multipart"
  12. "net/http"
  13. "os"
  14. "strconv"
  15. "strings"
  16. "testing"
  17. "time"
  18. "github.com/gin-gonic/gin/testdata/protoexample"
  19. "github.com/golang/protobuf/proto"
  20. "github.com/stretchr/testify/assert"
  21. "github.com/ugorji/go/codec"
  22. )
  23. type appkey struct {
  24. Appkey string `json:"appkey" form:"appkey"`
  25. }
  26. type QueryTest struct {
  27. Page int `json:"page" form:"page"`
  28. Size int `json:"size" form:"size"`
  29. appkey
  30. }
  31. type FooStruct struct {
  32. Foo string `msgpack:"foo" json:"foo" form:"foo" xml:"foo" binding:"required"`
  33. }
  34. type FooBarStruct struct {
  35. FooStruct
  36. Bar string `msgpack:"bar" json:"bar" form:"bar" xml:"bar" binding:"required"`
  37. }
  38. type FooBarFileStruct struct {
  39. FooBarStruct
  40. File *multipart.FileHeader `form:"file" binding:"required"`
  41. }
  42. type FooBarFileFailStruct struct {
  43. FooBarStruct
  44. File *multipart.FileHeader `invalid_name:"file" binding:"required"`
  45. // for unexport test
  46. data *multipart.FileHeader `form:"data" binding:"required"`
  47. }
  48. type FooDefaultBarStruct struct {
  49. FooStruct
  50. Bar string `msgpack:"bar" json:"bar" form:"bar,default=hello" xml:"bar" binding:"required"`
  51. }
  52. type FooStructUseNumber struct {
  53. Foo interface{} `json:"foo" binding:"required"`
  54. }
  55. type FooBarStructForTimeType struct {
  56. TimeFoo time.Time `form:"time_foo" time_format:"2006-01-02" time_utc:"1" time_location:"Asia/Chongqing"`
  57. TimeBar time.Time `form:"time_bar" time_format:"2006-01-02" time_utc:"1"`
  58. }
  59. type FooStructForTimeTypeNotFormat struct {
  60. TimeFoo time.Time `form:"time_foo"`
  61. }
  62. type FooStructForTimeTypeFailFormat struct {
  63. TimeFoo time.Time `form:"time_foo" time_format:"2017-11-15"`
  64. }
  65. type FooStructForTimeTypeFailLocation struct {
  66. TimeFoo time.Time `form:"time_foo" time_format:"2006-01-02" time_location:"/asia/chongqing"`
  67. }
  68. type FooStructForMapType struct {
  69. MapFoo map[string]interface{} `form:"map_foo"`
  70. }
  71. type FooStructForIgnoreFormTag struct {
  72. Foo *string `form:"-"`
  73. }
  74. type InvalidNameType struct {
  75. TestName string `invalid_name:"test_name"`
  76. }
  77. type InvalidNameMapType struct {
  78. TestName struct {
  79. MapFoo map[string]interface{} `form:"map_foo"`
  80. }
  81. }
  82. type FooStructForSliceType struct {
  83. SliceFoo []int `form:"slice_foo"`
  84. }
  85. type FooStructForStructType struct {
  86. StructFoo struct {
  87. Idx int `form:"idx"`
  88. }
  89. }
  90. type FooStructForStructPointerType struct {
  91. StructPointerFoo *struct {
  92. Name string `form:"name"`
  93. }
  94. }
  95. type FooStructForSliceMapType struct {
  96. // Unknown type: not support map
  97. SliceMapFoo []map[string]interface{} `form:"slice_map_foo"`
  98. }
  99. type FooStructForBoolType struct {
  100. BoolFoo bool `form:"bool_foo"`
  101. }
  102. type FooStructForStringPtrType struct {
  103. PtrFoo *string `form:"ptr_foo"`
  104. PtrBar *string `form:"ptr_bar" binding:"required"`
  105. }
  106. type FooStructForMapPtrType struct {
  107. PtrBar *map[string]interface{} `form:"ptr_bar"`
  108. }
  109. func TestBindingDefault(t *testing.T) {
  110. assert.Equal(t, Form, Default("GET", ""))
  111. assert.Equal(t, Form, Default("GET", MIMEJSON))
  112. assert.Equal(t, JSON, Default("POST", MIMEJSON))
  113. assert.Equal(t, JSON, Default("PUT", MIMEJSON))
  114. assert.Equal(t, XML, Default("POST", MIMEXML))
  115. assert.Equal(t, XML, Default("PUT", MIMEXML2))
  116. assert.Equal(t, Form, Default("POST", MIMEPOSTForm))
  117. assert.Equal(t, Form, Default("PUT", MIMEPOSTForm))
  118. assert.Equal(t, FormMultipart, Default("POST", MIMEMultipartPOSTForm))
  119. assert.Equal(t, FormMultipart, Default("PUT", MIMEMultipartPOSTForm))
  120. assert.Equal(t, ProtoBuf, Default("POST", MIMEPROTOBUF))
  121. assert.Equal(t, ProtoBuf, Default("PUT", MIMEPROTOBUF))
  122. assert.Equal(t, MsgPack, Default("POST", MIMEMSGPACK))
  123. assert.Equal(t, MsgPack, Default("PUT", MIMEMSGPACK2))
  124. assert.Equal(t, YAML, Default("POST", MIMEYAML))
  125. assert.Equal(t, YAML, Default("PUT", MIMEYAML))
  126. }
  127. func TestBindingJSONNilBody(t *testing.T) {
  128. var obj FooStruct
  129. req, _ := http.NewRequest(http.MethodPost, "/", nil)
  130. err := JSON.Bind(req, &obj)
  131. assert.Error(t, err)
  132. }
  133. func TestBindingJSON(t *testing.T) {
  134. testBodyBinding(t,
  135. JSON, "json",
  136. "/", "/",
  137. `{"foo": "bar"}`, `{"bar": "foo"}`)
  138. }
  139. func TestBindingJSONUseNumber(t *testing.T) {
  140. testBodyBindingUseNumber(t,
  141. JSON, "json",
  142. "/", "/",
  143. `{"foo": 123}`, `{"bar": "foo"}`)
  144. }
  145. func TestBindingJSONUseNumber2(t *testing.T) {
  146. testBodyBindingUseNumber2(t,
  147. JSON, "json",
  148. "/", "/",
  149. `{"foo": 123}`, `{"bar": "foo"}`)
  150. }
  151. func TestBindingForm(t *testing.T) {
  152. testFormBinding(t, "POST",
  153. "/", "/",
  154. "foo=bar&bar=foo", "bar2=foo")
  155. }
  156. func TestBindingForm2(t *testing.T) {
  157. testFormBinding(t, "GET",
  158. "/?foo=bar&bar=foo", "/?bar2=foo",
  159. "", "")
  160. }
  161. func TestBindingFormEmbeddedStruct(t *testing.T) {
  162. testFormBindingEmbeddedStruct(t, "POST",
  163. "/", "/",
  164. "page=1&size=2&appkey=test-appkey", "bar2=foo")
  165. }
  166. func TestBindingFormEmbeddedStruct2(t *testing.T) {
  167. testFormBindingEmbeddedStruct(t, "GET",
  168. "/?page=1&size=2&appkey=test-appkey", "/?bar2=foo",
  169. "", "")
  170. }
  171. func TestBindingFormDefaultValue(t *testing.T) {
  172. testFormBindingDefaultValue(t, "POST",
  173. "/", "/",
  174. "foo=bar", "bar2=foo")
  175. }
  176. func TestBindingFormDefaultValue2(t *testing.T) {
  177. testFormBindingDefaultValue(t, "GET",
  178. "/?foo=bar", "/?bar2=foo",
  179. "", "")
  180. }
  181. func TestBindingFormForTime(t *testing.T) {
  182. testFormBindingForTime(t, "POST",
  183. "/", "/",
  184. "time_foo=2017-11-15&time_bar=", "bar2=foo")
  185. testFormBindingForTimeNotFormat(t, "POST",
  186. "/", "/",
  187. "time_foo=2017-11-15", "bar2=foo")
  188. testFormBindingForTimeFailFormat(t, "POST",
  189. "/", "/",
  190. "time_foo=2017-11-15", "bar2=foo")
  191. testFormBindingForTimeFailLocation(t, "POST",
  192. "/", "/",
  193. "time_foo=2017-11-15", "bar2=foo")
  194. }
  195. func TestBindingFormForTime2(t *testing.T) {
  196. testFormBindingForTime(t, "GET",
  197. "/?time_foo=2017-11-15&time_bar=", "/?bar2=foo",
  198. "", "")
  199. testFormBindingForTimeNotFormat(t, "GET",
  200. "/?time_foo=2017-11-15", "/?bar2=foo",
  201. "", "")
  202. testFormBindingForTimeFailFormat(t, "GET",
  203. "/?time_foo=2017-11-15", "/?bar2=foo",
  204. "", "")
  205. testFormBindingForTimeFailLocation(t, "GET",
  206. "/?time_foo=2017-11-15", "/?bar2=foo",
  207. "", "")
  208. }
  209. func TestFormBindingIgnoreField(t *testing.T) {
  210. testFormBindingIgnoreField(t, "POST",
  211. "/", "/",
  212. "-=bar", "")
  213. }
  214. func TestBindingFormInvalidName(t *testing.T) {
  215. testFormBindingInvalidName(t, "POST",
  216. "/", "/",
  217. "test_name=bar", "bar2=foo")
  218. }
  219. func TestBindingFormInvalidName2(t *testing.T) {
  220. testFormBindingInvalidName2(t, "POST",
  221. "/", "/",
  222. "map_foo=bar", "bar2=foo")
  223. }
  224. func TestBindingFormForType(t *testing.T) {
  225. testFormBindingForType(t, "POST",
  226. "/", "/",
  227. "map_foo={\"bar\":123}", "map_foo=1", "Map")
  228. testFormBindingForType(t, "POST",
  229. "/", "/",
  230. "slice_foo=1&slice_foo=2", "bar2=1&bar2=2", "Slice")
  231. testFormBindingForType(t, "GET",
  232. "/?slice_foo=1&slice_foo=2", "/?bar2=1&bar2=2",
  233. "", "", "Slice")
  234. testFormBindingForType(t, "POST",
  235. "/", "/",
  236. "slice_map_foo=1&slice_map_foo=2", "bar2=1&bar2=2", "SliceMap")
  237. testFormBindingForType(t, "GET",
  238. "/?slice_map_foo=1&slice_map_foo=2", "/?bar2=1&bar2=2",
  239. "", "", "SliceMap")
  240. testFormBindingForType(t, "POST",
  241. "/", "/",
  242. "ptr_bar=test", "bar2=test", "Ptr")
  243. testFormBindingForType(t, "GET",
  244. "/?ptr_bar=test", "/?bar2=test",
  245. "", "", "Ptr")
  246. testFormBindingForType(t, "POST",
  247. "/", "/",
  248. "idx=123", "id1=1", "Struct")
  249. testFormBindingForType(t, "GET",
  250. "/?idx=123", "/?id1=1",
  251. "", "", "Struct")
  252. testFormBindingForType(t, "POST",
  253. "/", "/",
  254. "name=thinkerou", "name1=ou", "StructPointer")
  255. testFormBindingForType(t, "GET",
  256. "/?name=thinkerou", "/?name1=ou",
  257. "", "", "StructPointer")
  258. }
  259. func TestBindingQuery(t *testing.T) {
  260. testQueryBinding(t, "POST",
  261. "/?foo=bar&bar=foo", "/",
  262. "foo=unused", "bar2=foo")
  263. }
  264. func TestBindingQuery2(t *testing.T) {
  265. testQueryBinding(t, "GET",
  266. "/?foo=bar&bar=foo", "/?bar2=foo",
  267. "foo=unused", "")
  268. }
  269. func TestBindingQueryFail(t *testing.T) {
  270. testQueryBindingFail(t, "POST",
  271. "/?map_foo=", "/",
  272. "map_foo=unused", "bar2=foo")
  273. }
  274. func TestBindingQueryFail2(t *testing.T) {
  275. testQueryBindingFail(t, "GET",
  276. "/?map_foo=", "/?bar2=foo",
  277. "map_foo=unused", "")
  278. }
  279. func TestBindingQueryBoolFail(t *testing.T) {
  280. testQueryBindingBoolFail(t, "GET",
  281. "/?bool_foo=fasl", "/?bar2=foo",
  282. "bool_foo=unused", "")
  283. }
  284. func TestBindingXML(t *testing.T) {
  285. testBodyBinding(t,
  286. XML, "xml",
  287. "/", "/",
  288. "<map><foo>bar</foo></map>", "<map><bar>foo</bar></map>")
  289. }
  290. func TestBindingXMLFail(t *testing.T) {
  291. testBodyBindingFail(t,
  292. XML, "xml",
  293. "/", "/",
  294. "<map><foo>bar<foo></map>", "<map><bar>foo</bar></map>")
  295. }
  296. func TestBindingYAML(t *testing.T) {
  297. testBodyBinding(t,
  298. YAML, "yaml",
  299. "/", "/",
  300. `foo: bar`, `bar: foo`)
  301. }
  302. func TestBindingYAMLFail(t *testing.T) {
  303. testBodyBindingFail(t,
  304. YAML, "yaml",
  305. "/", "/",
  306. `foo:\nbar`, `bar: foo`)
  307. }
  308. func createFormPostRequest(t *testing.T) *http.Request {
  309. req, err := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", bytes.NewBufferString("foo=bar&bar=foo"))
  310. assert.NoError(t, err)
  311. req.Header.Set("Content-Type", MIMEPOSTForm)
  312. return req
  313. }
  314. func createDefaultFormPostRequest(t *testing.T) *http.Request {
  315. req, err := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", bytes.NewBufferString("foo=bar"))
  316. assert.NoError(t, err)
  317. req.Header.Set("Content-Type", MIMEPOSTForm)
  318. return req
  319. }
  320. func createFormPostRequestForMap(t *testing.T) *http.Request {
  321. req, err := http.NewRequest("POST", "/?map_foo=getfoo", bytes.NewBufferString("map_foo={\"bar\":123}"))
  322. assert.NoError(t, err)
  323. req.Header.Set("Content-Type", MIMEPOSTForm)
  324. return req
  325. }
  326. func createFormPostRequestForMapFail(t *testing.T) *http.Request {
  327. req, err := http.NewRequest("POST", "/?map_foo=getfoo", bytes.NewBufferString("map_foo=hello"))
  328. assert.NoError(t, err)
  329. req.Header.Set("Content-Type", MIMEPOSTForm)
  330. return req
  331. }
  332. func createFormFilesMultipartRequest(t *testing.T) *http.Request {
  333. boundary := "--testboundary"
  334. body := new(bytes.Buffer)
  335. mw := multipart.NewWriter(body)
  336. defer mw.Close()
  337. assert.NoError(t, mw.SetBoundary(boundary))
  338. assert.NoError(t, mw.WriteField("foo", "bar"))
  339. assert.NoError(t, mw.WriteField("bar", "foo"))
  340. f, err := os.Open("form.go")
  341. assert.NoError(t, err)
  342. defer f.Close()
  343. fw, err1 := mw.CreateFormFile("file", "form.go")
  344. assert.NoError(t, err1)
  345. io.Copy(fw, f)
  346. req, err2 := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", body)
  347. assert.NoError(t, err2)
  348. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  349. return req
  350. }
  351. func createFormFilesMultipartRequestFail(t *testing.T) *http.Request {
  352. boundary := "--testboundary"
  353. body := new(bytes.Buffer)
  354. mw := multipart.NewWriter(body)
  355. defer mw.Close()
  356. assert.NoError(t, mw.SetBoundary(boundary))
  357. assert.NoError(t, mw.WriteField("foo", "bar"))
  358. assert.NoError(t, mw.WriteField("bar", "foo"))
  359. f, err := os.Open("form.go")
  360. assert.NoError(t, err)
  361. defer f.Close()
  362. fw, err1 := mw.CreateFormFile("file_foo", "form_foo.go")
  363. assert.NoError(t, err1)
  364. io.Copy(fw, f)
  365. req, err2 := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", body)
  366. assert.NoError(t, err2)
  367. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  368. return req
  369. }
  370. func createFormMultipartRequest(t *testing.T) *http.Request {
  371. boundary := "--testboundary"
  372. body := new(bytes.Buffer)
  373. mw := multipart.NewWriter(body)
  374. defer mw.Close()
  375. assert.NoError(t, mw.SetBoundary(boundary))
  376. assert.NoError(t, mw.WriteField("foo", "bar"))
  377. assert.NoError(t, mw.WriteField("bar", "foo"))
  378. req, err := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", body)
  379. assert.NoError(t, err)
  380. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  381. return req
  382. }
  383. func createFormMultipartRequestForMap(t *testing.T) *http.Request {
  384. boundary := "--testboundary"
  385. body := new(bytes.Buffer)
  386. mw := multipart.NewWriter(body)
  387. defer mw.Close()
  388. assert.NoError(t, mw.SetBoundary(boundary))
  389. assert.NoError(t, mw.WriteField("map_foo", "{\"bar\":123, \"name\":\"thinkerou\", \"pai\": 3.14}"))
  390. req, err := http.NewRequest("POST", "/?map_foo=getfoo", body)
  391. assert.NoError(t, err)
  392. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  393. return req
  394. }
  395. func createFormMultipartRequestForMapFail(t *testing.T) *http.Request {
  396. boundary := "--testboundary"
  397. body := new(bytes.Buffer)
  398. mw := multipart.NewWriter(body)
  399. defer mw.Close()
  400. assert.NoError(t, mw.SetBoundary(boundary))
  401. assert.NoError(t, mw.WriteField("map_foo", "3.14"))
  402. req, err := http.NewRequest("POST", "/?map_foo=getfoo", body)
  403. assert.NoError(t, err)
  404. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  405. return req
  406. }
  407. func TestBindingFormPost(t *testing.T) {
  408. req := createFormPostRequest(t)
  409. var obj FooBarStruct
  410. assert.NoError(t, FormPost.Bind(req, &obj))
  411. assert.Equal(t, "form-urlencoded", FormPost.Name())
  412. assert.Equal(t, "bar", obj.Foo)
  413. assert.Equal(t, "foo", obj.Bar)
  414. }
  415. func TestBindingDefaultValueFormPost(t *testing.T) {
  416. req := createDefaultFormPostRequest(t)
  417. var obj FooDefaultBarStruct
  418. assert.NoError(t, FormPost.Bind(req, &obj))
  419. assert.Equal(t, "bar", obj.Foo)
  420. assert.Equal(t, "hello", obj.Bar)
  421. }
  422. func TestBindingFormPostForMap(t *testing.T) {
  423. req := createFormPostRequestForMap(t)
  424. var obj FooStructForMapType
  425. err := FormPost.Bind(req, &obj)
  426. assert.NoError(t, err)
  427. assert.Equal(t, float64(123), obj.MapFoo["bar"].(float64))
  428. }
  429. func TestBindingFormPostForMapFail(t *testing.T) {
  430. req := createFormPostRequestForMapFail(t)
  431. var obj FooStructForMapType
  432. err := FormPost.Bind(req, &obj)
  433. assert.Error(t, err)
  434. }
  435. func TestBindingFormFilesMultipart(t *testing.T) {
  436. req := createFormFilesMultipartRequest(t)
  437. var obj FooBarFileStruct
  438. FormMultipart.Bind(req, &obj)
  439. // file from os
  440. f, _ := os.Open("form.go")
  441. defer f.Close()
  442. fileActual, _ := ioutil.ReadAll(f)
  443. // file from multipart
  444. mf, _ := obj.File.Open()
  445. defer mf.Close()
  446. fileExpect, _ := ioutil.ReadAll(mf)
  447. assert.Equal(t, FormMultipart.Name(), "multipart/form-data")
  448. assert.Equal(t, obj.Foo, "bar")
  449. assert.Equal(t, obj.Bar, "foo")
  450. assert.Equal(t, fileExpect, fileActual)
  451. }
  452. func TestBindingFormFilesMultipartFail(t *testing.T) {
  453. req := createFormFilesMultipartRequestFail(t)
  454. var obj FooBarFileFailStruct
  455. err := FormMultipart.Bind(req, &obj)
  456. assert.Error(t, err)
  457. }
  458. func TestBindingFormMultipart(t *testing.T) {
  459. req := createFormMultipartRequest(t)
  460. var obj FooBarStruct
  461. assert.NoError(t, FormMultipart.Bind(req, &obj))
  462. assert.Equal(t, "multipart/form-data", FormMultipart.Name())
  463. assert.Equal(t, "bar", obj.Foo)
  464. assert.Equal(t, "foo", obj.Bar)
  465. }
  466. func TestBindingFormMultipartForMap(t *testing.T) {
  467. req := createFormMultipartRequestForMap(t)
  468. var obj FooStructForMapType
  469. err := FormMultipart.Bind(req, &obj)
  470. assert.NoError(t, err)
  471. assert.Equal(t, float64(123), obj.MapFoo["bar"].(float64))
  472. assert.Equal(t, "thinkerou", obj.MapFoo["name"].(string))
  473. assert.Equal(t, float64(3.14), obj.MapFoo["pai"].(float64))
  474. }
  475. func TestBindingFormMultipartForMapFail(t *testing.T) {
  476. req := createFormMultipartRequestForMapFail(t)
  477. var obj FooStructForMapType
  478. err := FormMultipart.Bind(req, &obj)
  479. assert.Error(t, err)
  480. }
  481. func TestBindingProtoBuf(t *testing.T) {
  482. test := &protoexample.Test{
  483. Label: proto.String("yes"),
  484. }
  485. data, _ := proto.Marshal(test)
  486. testProtoBodyBinding(t,
  487. ProtoBuf, "protobuf",
  488. "/", "/",
  489. string(data), string(data[1:]))
  490. }
  491. func TestBindingProtoBufFail(t *testing.T) {
  492. test := &protoexample.Test{
  493. Label: proto.String("yes"),
  494. }
  495. data, _ := proto.Marshal(test)
  496. testProtoBodyBindingFail(t,
  497. ProtoBuf, "protobuf",
  498. "/", "/",
  499. string(data), string(data[1:]))
  500. }
  501. func TestBindingMsgPack(t *testing.T) {
  502. test := FooStruct{
  503. Foo: "bar",
  504. }
  505. h := new(codec.MsgpackHandle)
  506. assert.NotNil(t, h)
  507. buf := bytes.NewBuffer([]byte{})
  508. assert.NotNil(t, buf)
  509. err := codec.NewEncoder(buf, h).Encode(test)
  510. assert.NoError(t, err)
  511. data := buf.Bytes()
  512. testMsgPackBodyBinding(t,
  513. MsgPack, "msgpack",
  514. "/", "/",
  515. string(data), string(data[1:]))
  516. }
  517. func TestValidationFails(t *testing.T) {
  518. var obj FooStruct
  519. req := requestWithBody("POST", "/", `{"bar": "foo"}`)
  520. err := JSON.Bind(req, &obj)
  521. assert.Error(t, err)
  522. }
  523. func TestValidationDisabled(t *testing.T) {
  524. backup := Validator
  525. Validator = nil
  526. defer func() { Validator = backup }()
  527. var obj FooStruct
  528. req := requestWithBody("POST", "/", `{"bar": "foo"}`)
  529. err := JSON.Bind(req, &obj)
  530. assert.NoError(t, err)
  531. }
  532. func TestExistsSucceeds(t *testing.T) {
  533. type HogeStruct struct {
  534. Hoge *int `json:"hoge" binding:"exists"`
  535. }
  536. var obj HogeStruct
  537. req := requestWithBody("POST", "/", `{"hoge": 0}`)
  538. err := JSON.Bind(req, &obj)
  539. assert.NoError(t, err)
  540. }
  541. func TestExistsFails(t *testing.T) {
  542. type HogeStruct struct {
  543. Hoge *int `json:"foo" binding:"exists"`
  544. }
  545. var obj HogeStruct
  546. req := requestWithBody("POST", "/", `{"boen": 0}`)
  547. err := JSON.Bind(req, &obj)
  548. assert.Error(t, err)
  549. }
  550. func TestUriBinding(t *testing.T) {
  551. b := Uri
  552. assert.Equal(t, "uri", b.Name())
  553. type Tag struct {
  554. Name string `uri:"name"`
  555. }
  556. var tag Tag
  557. m := make(map[string][]string)
  558. m["name"] = []string{"thinkerou"}
  559. assert.NoError(t, b.BindUri(m, &tag))
  560. assert.Equal(t, "thinkerou", tag.Name)
  561. type NotSupportStruct struct {
  562. Name map[string]interface{} `uri:"name"`
  563. }
  564. var not NotSupportStruct
  565. assert.Error(t, b.BindUri(m, &not))
  566. assert.Equal(t, map[string]interface{}(nil), not.Name)
  567. }
  568. func TestUriInnerBinding(t *testing.T) {
  569. type Tag struct {
  570. Name string `uri:"name"`
  571. S struct {
  572. Age int `uri:"age"`
  573. }
  574. }
  575. expectedName := "mike"
  576. expectedAge := 25
  577. m := map[string][]string{
  578. "name": {expectedName},
  579. "age": {strconv.Itoa(expectedAge)},
  580. }
  581. var tag Tag
  582. assert.NoError(t, Uri.BindUri(m, &tag))
  583. assert.Equal(t, tag.Name, expectedName)
  584. assert.Equal(t, tag.S.Age, expectedAge)
  585. }
  586. func testFormBindingEmbeddedStruct(t *testing.T, method, path, badPath, body, badBody string) {
  587. b := Form
  588. assert.Equal(t, "form", b.Name())
  589. obj := QueryTest{}
  590. req := requestWithBody(method, path, body)
  591. if method == "POST" {
  592. req.Header.Add("Content-Type", MIMEPOSTForm)
  593. }
  594. err := b.Bind(req, &obj)
  595. assert.NoError(t, err)
  596. assert.Equal(t, 1, obj.Page)
  597. assert.Equal(t, 2, obj.Size)
  598. assert.Equal(t, "test-appkey", obj.Appkey)
  599. }
  600. func testFormBinding(t *testing.T, method, path, badPath, body, badBody string) {
  601. b := Form
  602. assert.Equal(t, "form", b.Name())
  603. obj := FooBarStruct{}
  604. req := requestWithBody(method, path, body)
  605. if method == "POST" {
  606. req.Header.Add("Content-Type", MIMEPOSTForm)
  607. }
  608. err := b.Bind(req, &obj)
  609. assert.NoError(t, err)
  610. assert.Equal(t, "bar", obj.Foo)
  611. assert.Equal(t, "foo", obj.Bar)
  612. obj = FooBarStruct{}
  613. req = requestWithBody(method, badPath, badBody)
  614. err = JSON.Bind(req, &obj)
  615. assert.Error(t, err)
  616. }
  617. func testFormBindingDefaultValue(t *testing.T, method, path, badPath, body, badBody string) {
  618. b := Form
  619. assert.Equal(t, "form", b.Name())
  620. obj := FooDefaultBarStruct{}
  621. req := requestWithBody(method, path, body)
  622. if method == "POST" {
  623. req.Header.Add("Content-Type", MIMEPOSTForm)
  624. }
  625. err := b.Bind(req, &obj)
  626. assert.NoError(t, err)
  627. assert.Equal(t, "bar", obj.Foo)
  628. assert.Equal(t, "hello", obj.Bar)
  629. obj = FooDefaultBarStruct{}
  630. req = requestWithBody(method, badPath, badBody)
  631. err = JSON.Bind(req, &obj)
  632. assert.Error(t, err)
  633. }
  634. func TestFormBindingFail(t *testing.T) {
  635. b := Form
  636. assert.Equal(t, "form", b.Name())
  637. obj := FooBarStruct{}
  638. req, _ := http.NewRequest("POST", "/", nil)
  639. err := b.Bind(req, &obj)
  640. assert.Error(t, err)
  641. }
  642. func TestFormBindingMultipartFail(t *testing.T) {
  643. obj := FooBarStruct{}
  644. req, err := http.NewRequest("POST", "/", strings.NewReader("foo=bar"))
  645. assert.NoError(t, err)
  646. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+";boundary=testboundary")
  647. _, err = req.MultipartReader()
  648. assert.NoError(t, err)
  649. err = Form.Bind(req, &obj)
  650. assert.Error(t, err)
  651. }
  652. func TestFormPostBindingFail(t *testing.T) {
  653. b := FormPost
  654. assert.Equal(t, "form-urlencoded", b.Name())
  655. obj := FooBarStruct{}
  656. req, _ := http.NewRequest("POST", "/", nil)
  657. err := b.Bind(req, &obj)
  658. assert.Error(t, err)
  659. }
  660. func TestFormMultipartBindingFail(t *testing.T) {
  661. b := FormMultipart
  662. assert.Equal(t, "multipart/form-data", b.Name())
  663. obj := FooBarStruct{}
  664. req, _ := http.NewRequest("POST", "/", nil)
  665. err := b.Bind(req, &obj)
  666. assert.Error(t, err)
  667. }
  668. func testFormBindingForTime(t *testing.T, method, path, badPath, body, badBody string) {
  669. b := Form
  670. assert.Equal(t, "form", b.Name())
  671. obj := FooBarStructForTimeType{}
  672. req := requestWithBody(method, path, body)
  673. if method == "POST" {
  674. req.Header.Add("Content-Type", MIMEPOSTForm)
  675. }
  676. err := b.Bind(req, &obj)
  677. assert.NoError(t, err)
  678. assert.Equal(t, int64(1510675200), obj.TimeFoo.Unix())
  679. assert.Equal(t, "Asia/Chongqing", obj.TimeFoo.Location().String())
  680. assert.Equal(t, int64(-62135596800), obj.TimeBar.Unix())
  681. assert.Equal(t, "UTC", obj.TimeBar.Location().String())
  682. obj = FooBarStructForTimeType{}
  683. req = requestWithBody(method, badPath, badBody)
  684. err = JSON.Bind(req, &obj)
  685. assert.Error(t, err)
  686. }
  687. func testFormBindingForTimeNotFormat(t *testing.T, method, path, badPath, body, badBody string) {
  688. b := Form
  689. assert.Equal(t, "form", b.Name())
  690. obj := FooStructForTimeTypeNotFormat{}
  691. req := requestWithBody(method, path, body)
  692. if method == "POST" {
  693. req.Header.Add("Content-Type", MIMEPOSTForm)
  694. }
  695. err := b.Bind(req, &obj)
  696. assert.Error(t, err)
  697. obj = FooStructForTimeTypeNotFormat{}
  698. req = requestWithBody(method, badPath, badBody)
  699. err = JSON.Bind(req, &obj)
  700. assert.Error(t, err)
  701. }
  702. func testFormBindingForTimeFailFormat(t *testing.T, method, path, badPath, body, badBody string) {
  703. b := Form
  704. assert.Equal(t, "form", b.Name())
  705. obj := FooStructForTimeTypeFailFormat{}
  706. req := requestWithBody(method, path, body)
  707. if method == "POST" {
  708. req.Header.Add("Content-Type", MIMEPOSTForm)
  709. }
  710. err := b.Bind(req, &obj)
  711. assert.Error(t, err)
  712. obj = FooStructForTimeTypeFailFormat{}
  713. req = requestWithBody(method, badPath, badBody)
  714. err = JSON.Bind(req, &obj)
  715. assert.Error(t, err)
  716. }
  717. func testFormBindingForTimeFailLocation(t *testing.T, method, path, badPath, body, badBody string) {
  718. b := Form
  719. assert.Equal(t, "form", b.Name())
  720. obj := FooStructForTimeTypeFailLocation{}
  721. req := requestWithBody(method, path, body)
  722. if method == "POST" {
  723. req.Header.Add("Content-Type", MIMEPOSTForm)
  724. }
  725. err := b.Bind(req, &obj)
  726. assert.Error(t, err)
  727. obj = FooStructForTimeTypeFailLocation{}
  728. req = requestWithBody(method, badPath, badBody)
  729. err = JSON.Bind(req, &obj)
  730. assert.Error(t, err)
  731. }
  732. func testFormBindingIgnoreField(t *testing.T, method, path, badPath, body, badBody string) {
  733. b := Form
  734. assert.Equal(t, "form", b.Name())
  735. obj := FooStructForIgnoreFormTag{}
  736. req := requestWithBody(method, path, body)
  737. if method == "POST" {
  738. req.Header.Add("Content-Type", MIMEPOSTForm)
  739. }
  740. err := b.Bind(req, &obj)
  741. assert.NoError(t, err)
  742. assert.Nil(t, obj.Foo)
  743. }
  744. func testFormBindingInvalidName(t *testing.T, method, path, badPath, body, badBody string) {
  745. b := Form
  746. assert.Equal(t, "form", b.Name())
  747. obj := InvalidNameType{}
  748. req := requestWithBody(method, path, body)
  749. if method == "POST" {
  750. req.Header.Add("Content-Type", MIMEPOSTForm)
  751. }
  752. err := b.Bind(req, &obj)
  753. assert.NoError(t, err)
  754. assert.Equal(t, "", obj.TestName)
  755. obj = InvalidNameType{}
  756. req = requestWithBody(method, badPath, badBody)
  757. err = JSON.Bind(req, &obj)
  758. assert.Error(t, err)
  759. }
  760. func testFormBindingInvalidName2(t *testing.T, method, path, badPath, body, badBody string) {
  761. b := Form
  762. assert.Equal(t, "form", b.Name())
  763. obj := InvalidNameMapType{}
  764. req := requestWithBody(method, path, body)
  765. if method == "POST" {
  766. req.Header.Add("Content-Type", MIMEPOSTForm)
  767. }
  768. err := b.Bind(req, &obj)
  769. assert.Error(t, err)
  770. obj = InvalidNameMapType{}
  771. req = requestWithBody(method, badPath, badBody)
  772. err = JSON.Bind(req, &obj)
  773. assert.Error(t, err)
  774. }
  775. func testFormBindingForType(t *testing.T, method, path, badPath, body, badBody string, typ string) {
  776. b := Form
  777. assert.Equal(t, "form", b.Name())
  778. req := requestWithBody(method, path, body)
  779. if method == "POST" {
  780. req.Header.Add("Content-Type", MIMEPOSTForm)
  781. }
  782. switch typ {
  783. case "Slice":
  784. obj := FooStructForSliceType{}
  785. err := b.Bind(req, &obj)
  786. assert.NoError(t, err)
  787. assert.Equal(t, []int{1, 2}, obj.SliceFoo)
  788. obj = FooStructForSliceType{}
  789. req = requestWithBody(method, badPath, badBody)
  790. err = JSON.Bind(req, &obj)
  791. assert.Error(t, err)
  792. case "Struct":
  793. obj := FooStructForStructType{}
  794. err := b.Bind(req, &obj)
  795. assert.NoError(t, err)
  796. assert.Equal(t,
  797. struct {
  798. Idx int "form:\"idx\""
  799. }(struct {
  800. Idx int "form:\"idx\""
  801. }{Idx: 123}),
  802. obj.StructFoo)
  803. case "StructPointer":
  804. obj := FooStructForStructPointerType{}
  805. err := b.Bind(req, &obj)
  806. assert.NoError(t, err)
  807. assert.Equal(t,
  808. struct {
  809. Name string "form:\"name\""
  810. }(struct {
  811. Name string "form:\"name\""
  812. }{Name: "thinkerou"}),
  813. *obj.StructPointerFoo)
  814. case "Map":
  815. obj := FooStructForMapType{}
  816. err := b.Bind(req, &obj)
  817. assert.NoError(t, err)
  818. assert.Equal(t, float64(123), obj.MapFoo["bar"].(float64))
  819. case "SliceMap":
  820. obj := FooStructForSliceMapType{}
  821. err := b.Bind(req, &obj)
  822. assert.Error(t, err)
  823. case "Ptr":
  824. obj := FooStructForStringPtrType{}
  825. err := b.Bind(req, &obj)
  826. assert.NoError(t, err)
  827. assert.Nil(t, obj.PtrFoo)
  828. assert.Equal(t, "test", *obj.PtrBar)
  829. obj = FooStructForStringPtrType{}
  830. obj.PtrBar = new(string)
  831. err = b.Bind(req, &obj)
  832. assert.NoError(t, err)
  833. assert.Equal(t, "test", *obj.PtrBar)
  834. objErr := FooStructForMapPtrType{}
  835. err = b.Bind(req, &objErr)
  836. assert.Error(t, err)
  837. obj = FooStructForStringPtrType{}
  838. req = requestWithBody(method, badPath, badBody)
  839. err = b.Bind(req, &obj)
  840. assert.Error(t, err)
  841. }
  842. }
  843. func testQueryBinding(t *testing.T, method, path, badPath, body, badBody string) {
  844. b := Query
  845. assert.Equal(t, "query", b.Name())
  846. obj := FooBarStruct{}
  847. req := requestWithBody(method, path, body)
  848. if method == "POST" {
  849. req.Header.Add("Content-Type", MIMEPOSTForm)
  850. }
  851. err := b.Bind(req, &obj)
  852. assert.NoError(t, err)
  853. assert.Equal(t, "bar", obj.Foo)
  854. assert.Equal(t, "foo", obj.Bar)
  855. }
  856. func testQueryBindingFail(t *testing.T, method, path, badPath, body, badBody string) {
  857. b := Query
  858. assert.Equal(t, "query", b.Name())
  859. obj := FooStructForMapType{}
  860. req := requestWithBody(method, path, body)
  861. if method == "POST" {
  862. req.Header.Add("Content-Type", MIMEPOSTForm)
  863. }
  864. err := b.Bind(req, &obj)
  865. assert.Error(t, err)
  866. }
  867. func testQueryBindingBoolFail(t *testing.T, method, path, badPath, body, badBody string) {
  868. b := Query
  869. assert.Equal(t, "query", b.Name())
  870. obj := FooStructForBoolType{}
  871. req := requestWithBody(method, path, body)
  872. if method == "POST" {
  873. req.Header.Add("Content-Type", MIMEPOSTForm)
  874. }
  875. err := b.Bind(req, &obj)
  876. assert.Error(t, err)
  877. }
  878. func testBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  879. assert.Equal(t, name, b.Name())
  880. obj := FooStruct{}
  881. req := requestWithBody("POST", path, body)
  882. err := b.Bind(req, &obj)
  883. assert.NoError(t, err)
  884. assert.Equal(t, "bar", obj.Foo)
  885. obj = FooStruct{}
  886. req = requestWithBody("POST", badPath, badBody)
  887. err = JSON.Bind(req, &obj)
  888. assert.Error(t, err)
  889. }
  890. func testBodyBindingUseNumber(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  891. assert.Equal(t, name, b.Name())
  892. obj := FooStructUseNumber{}
  893. req := requestWithBody("POST", path, body)
  894. EnableDecoderUseNumber = true
  895. err := b.Bind(req, &obj)
  896. assert.NoError(t, err)
  897. // we hope it is int64(123)
  898. v, e := obj.Foo.(json.Number).Int64()
  899. assert.NoError(t, e)
  900. assert.Equal(t, int64(123), v)
  901. obj = FooStructUseNumber{}
  902. req = requestWithBody("POST", badPath, badBody)
  903. err = JSON.Bind(req, &obj)
  904. assert.Error(t, err)
  905. }
  906. func testBodyBindingUseNumber2(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  907. assert.Equal(t, name, b.Name())
  908. obj := FooStructUseNumber{}
  909. req := requestWithBody("POST", path, body)
  910. EnableDecoderUseNumber = false
  911. err := b.Bind(req, &obj)
  912. assert.NoError(t, err)
  913. // it will return float64(123) if not use EnableDecoderUseNumber
  914. // maybe it is not hoped
  915. assert.Equal(t, float64(123), obj.Foo)
  916. obj = FooStructUseNumber{}
  917. req = requestWithBody("POST", badPath, badBody)
  918. err = JSON.Bind(req, &obj)
  919. assert.Error(t, err)
  920. }
  921. func testBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  922. assert.Equal(t, name, b.Name())
  923. obj := FooStruct{}
  924. req := requestWithBody("POST", path, body)
  925. err := b.Bind(req, &obj)
  926. assert.Error(t, err)
  927. assert.Equal(t, "", obj.Foo)
  928. obj = FooStruct{}
  929. req = requestWithBody("POST", badPath, badBody)
  930. err = JSON.Bind(req, &obj)
  931. assert.Error(t, err)
  932. }
  933. func testProtoBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  934. assert.Equal(t, name, b.Name())
  935. obj := protoexample.Test{}
  936. req := requestWithBody("POST", path, body)
  937. req.Header.Add("Content-Type", MIMEPROTOBUF)
  938. err := b.Bind(req, &obj)
  939. assert.NoError(t, err)
  940. assert.Equal(t, "yes", *obj.Label)
  941. obj = protoexample.Test{}
  942. req = requestWithBody("POST", badPath, badBody)
  943. req.Header.Add("Content-Type", MIMEPROTOBUF)
  944. err = ProtoBuf.Bind(req, &obj)
  945. assert.Error(t, err)
  946. }
  947. type hook struct{}
  948. func (h hook) Read([]byte) (int, error) {
  949. return 0, errors.New("error")
  950. }
  951. func testProtoBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  952. assert.Equal(t, name, b.Name())
  953. obj := protoexample.Test{}
  954. req := requestWithBody("POST", path, body)
  955. req.Body = ioutil.NopCloser(&hook{})
  956. req.Header.Add("Content-Type", MIMEPROTOBUF)
  957. err := b.Bind(req, &obj)
  958. assert.Error(t, err)
  959. obj = protoexample.Test{}
  960. req = requestWithBody("POST", badPath, badBody)
  961. req.Header.Add("Content-Type", MIMEPROTOBUF)
  962. err = ProtoBuf.Bind(req, &obj)
  963. assert.Error(t, err)
  964. }
  965. func testMsgPackBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  966. assert.Equal(t, name, b.Name())
  967. obj := FooStruct{}
  968. req := requestWithBody("POST", path, body)
  969. req.Header.Add("Content-Type", MIMEMSGPACK)
  970. err := b.Bind(req, &obj)
  971. assert.NoError(t, err)
  972. assert.Equal(t, "bar", obj.Foo)
  973. obj = FooStruct{}
  974. req = requestWithBody("POST", badPath, badBody)
  975. req.Header.Add("Content-Type", MIMEMSGPACK)
  976. err = MsgPack.Bind(req, &obj)
  977. assert.Error(t, err)
  978. }
  979. func requestWithBody(method, path, body string) (req *http.Request) {
  980. req, _ = http.NewRequest(method, path, bytes.NewBufferString(body))
  981. return
  982. }