binding_test.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  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 TestHeaderBinding(t *testing.T) {
  551. h := Header
  552. assert.Equal(t, "header", h.Name())
  553. type tHeader struct {
  554. Limit int `header:"limit"`
  555. }
  556. var theader tHeader
  557. req := requestWithBody("GET", "/", "")
  558. req.Header.Add("limit", "1000")
  559. assert.NoError(t, h.Bind(req, &theader))
  560. assert.Equal(t, 1000, theader.Limit)
  561. req = requestWithBody("GET", "/", "")
  562. req.Header.Add("fail", `{fail:fail}`)
  563. type failStruct struct {
  564. Fail map[string]interface{} `header:"fail"`
  565. }
  566. err := h.Bind(req, &failStruct{})
  567. assert.Error(t, err)
  568. }
  569. func TestUriBinding(t *testing.T) {
  570. b := Uri
  571. assert.Equal(t, "uri", b.Name())
  572. type Tag struct {
  573. Name string `uri:"name"`
  574. }
  575. var tag Tag
  576. m := make(map[string][]string)
  577. m["name"] = []string{"thinkerou"}
  578. assert.NoError(t, b.BindUri(m, &tag))
  579. assert.Equal(t, "thinkerou", tag.Name)
  580. type NotSupportStruct struct {
  581. Name map[string]interface{} `uri:"name"`
  582. }
  583. var not NotSupportStruct
  584. assert.Error(t, b.BindUri(m, &not))
  585. assert.Equal(t, map[string]interface{}(nil), not.Name)
  586. }
  587. func TestUriInnerBinding(t *testing.T) {
  588. type Tag struct {
  589. Name string `uri:"name"`
  590. S struct {
  591. Age int `uri:"age"`
  592. }
  593. }
  594. expectedName := "mike"
  595. expectedAge := 25
  596. m := map[string][]string{
  597. "name": {expectedName},
  598. "age": {strconv.Itoa(expectedAge)},
  599. }
  600. var tag Tag
  601. assert.NoError(t, Uri.BindUri(m, &tag))
  602. assert.Equal(t, tag.Name, expectedName)
  603. assert.Equal(t, tag.S.Age, expectedAge)
  604. }
  605. func testFormBindingEmbeddedStruct(t *testing.T, method, path, badPath, body, badBody string) {
  606. b := Form
  607. assert.Equal(t, "form", b.Name())
  608. obj := QueryTest{}
  609. req := requestWithBody(method, path, body)
  610. if method == "POST" {
  611. req.Header.Add("Content-Type", MIMEPOSTForm)
  612. }
  613. err := b.Bind(req, &obj)
  614. assert.NoError(t, err)
  615. assert.Equal(t, 1, obj.Page)
  616. assert.Equal(t, 2, obj.Size)
  617. assert.Equal(t, "test-appkey", obj.Appkey)
  618. }
  619. func testFormBinding(t *testing.T, method, path, badPath, body, badBody string) {
  620. b := Form
  621. assert.Equal(t, "form", b.Name())
  622. obj := FooBarStruct{}
  623. req := requestWithBody(method, path, body)
  624. if method == "POST" {
  625. req.Header.Add("Content-Type", MIMEPOSTForm)
  626. }
  627. err := b.Bind(req, &obj)
  628. assert.NoError(t, err)
  629. assert.Equal(t, "bar", obj.Foo)
  630. assert.Equal(t, "foo", obj.Bar)
  631. obj = FooBarStruct{}
  632. req = requestWithBody(method, badPath, badBody)
  633. err = JSON.Bind(req, &obj)
  634. assert.Error(t, err)
  635. }
  636. func testFormBindingDefaultValue(t *testing.T, method, path, badPath, body, badBody string) {
  637. b := Form
  638. assert.Equal(t, "form", b.Name())
  639. obj := FooDefaultBarStruct{}
  640. req := requestWithBody(method, path, body)
  641. if method == "POST" {
  642. req.Header.Add("Content-Type", MIMEPOSTForm)
  643. }
  644. err := b.Bind(req, &obj)
  645. assert.NoError(t, err)
  646. assert.Equal(t, "bar", obj.Foo)
  647. assert.Equal(t, "hello", obj.Bar)
  648. obj = FooDefaultBarStruct{}
  649. req = requestWithBody(method, badPath, badBody)
  650. err = JSON.Bind(req, &obj)
  651. assert.Error(t, err)
  652. }
  653. func TestFormBindingFail(t *testing.T) {
  654. b := Form
  655. assert.Equal(t, "form", b.Name())
  656. obj := FooBarStruct{}
  657. req, _ := http.NewRequest("POST", "/", nil)
  658. err := b.Bind(req, &obj)
  659. assert.Error(t, err)
  660. }
  661. func TestFormBindingMultipartFail(t *testing.T) {
  662. obj := FooBarStruct{}
  663. req, err := http.NewRequest("POST", "/", strings.NewReader("foo=bar"))
  664. assert.NoError(t, err)
  665. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+";boundary=testboundary")
  666. _, err = req.MultipartReader()
  667. assert.NoError(t, err)
  668. err = Form.Bind(req, &obj)
  669. assert.Error(t, err)
  670. }
  671. func TestFormPostBindingFail(t *testing.T) {
  672. b := FormPost
  673. assert.Equal(t, "form-urlencoded", b.Name())
  674. obj := FooBarStruct{}
  675. req, _ := http.NewRequest("POST", "/", nil)
  676. err := b.Bind(req, &obj)
  677. assert.Error(t, err)
  678. }
  679. func TestFormMultipartBindingFail(t *testing.T) {
  680. b := FormMultipart
  681. assert.Equal(t, "multipart/form-data", b.Name())
  682. obj := FooBarStruct{}
  683. req, _ := http.NewRequest("POST", "/", nil)
  684. err := b.Bind(req, &obj)
  685. assert.Error(t, err)
  686. }
  687. func testFormBindingForTime(t *testing.T, method, path, badPath, body, badBody string) {
  688. b := Form
  689. assert.Equal(t, "form", b.Name())
  690. obj := FooBarStructForTimeType{}
  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.NoError(t, err)
  697. assert.Equal(t, int64(1510675200), obj.TimeFoo.Unix())
  698. assert.Equal(t, "Asia/Chongqing", obj.TimeFoo.Location().String())
  699. assert.Equal(t, int64(-62135596800), obj.TimeBar.Unix())
  700. assert.Equal(t, "UTC", obj.TimeBar.Location().String())
  701. obj = FooBarStructForTimeType{}
  702. req = requestWithBody(method, badPath, badBody)
  703. err = JSON.Bind(req, &obj)
  704. assert.Error(t, err)
  705. }
  706. func testFormBindingForTimeNotFormat(t *testing.T, method, path, badPath, body, badBody string) {
  707. b := Form
  708. assert.Equal(t, "form", b.Name())
  709. obj := FooStructForTimeTypeNotFormat{}
  710. req := requestWithBody(method, path, body)
  711. if method == "POST" {
  712. req.Header.Add("Content-Type", MIMEPOSTForm)
  713. }
  714. err := b.Bind(req, &obj)
  715. assert.Error(t, err)
  716. obj = FooStructForTimeTypeNotFormat{}
  717. req = requestWithBody(method, badPath, badBody)
  718. err = JSON.Bind(req, &obj)
  719. assert.Error(t, err)
  720. }
  721. func testFormBindingForTimeFailFormat(t *testing.T, method, path, badPath, body, badBody string) {
  722. b := Form
  723. assert.Equal(t, "form", b.Name())
  724. obj := FooStructForTimeTypeFailFormat{}
  725. req := requestWithBody(method, path, body)
  726. if method == "POST" {
  727. req.Header.Add("Content-Type", MIMEPOSTForm)
  728. }
  729. err := b.Bind(req, &obj)
  730. assert.Error(t, err)
  731. obj = FooStructForTimeTypeFailFormat{}
  732. req = requestWithBody(method, badPath, badBody)
  733. err = JSON.Bind(req, &obj)
  734. assert.Error(t, err)
  735. }
  736. func testFormBindingForTimeFailLocation(t *testing.T, method, path, badPath, body, badBody string) {
  737. b := Form
  738. assert.Equal(t, "form", b.Name())
  739. obj := FooStructForTimeTypeFailLocation{}
  740. req := requestWithBody(method, path, body)
  741. if method == "POST" {
  742. req.Header.Add("Content-Type", MIMEPOSTForm)
  743. }
  744. err := b.Bind(req, &obj)
  745. assert.Error(t, err)
  746. obj = FooStructForTimeTypeFailLocation{}
  747. req = requestWithBody(method, badPath, badBody)
  748. err = JSON.Bind(req, &obj)
  749. assert.Error(t, err)
  750. }
  751. func testFormBindingIgnoreField(t *testing.T, method, path, badPath, body, badBody string) {
  752. b := Form
  753. assert.Equal(t, "form", b.Name())
  754. obj := FooStructForIgnoreFormTag{}
  755. req := requestWithBody(method, path, body)
  756. if method == "POST" {
  757. req.Header.Add("Content-Type", MIMEPOSTForm)
  758. }
  759. err := b.Bind(req, &obj)
  760. assert.NoError(t, err)
  761. assert.Nil(t, obj.Foo)
  762. }
  763. func testFormBindingInvalidName(t *testing.T, method, path, badPath, body, badBody string) {
  764. b := Form
  765. assert.Equal(t, "form", b.Name())
  766. obj := InvalidNameType{}
  767. req := requestWithBody(method, path, body)
  768. if method == "POST" {
  769. req.Header.Add("Content-Type", MIMEPOSTForm)
  770. }
  771. err := b.Bind(req, &obj)
  772. assert.NoError(t, err)
  773. assert.Equal(t, "", obj.TestName)
  774. obj = InvalidNameType{}
  775. req = requestWithBody(method, badPath, badBody)
  776. err = JSON.Bind(req, &obj)
  777. assert.Error(t, err)
  778. }
  779. func testFormBindingInvalidName2(t *testing.T, method, path, badPath, body, badBody string) {
  780. b := Form
  781. assert.Equal(t, "form", b.Name())
  782. obj := InvalidNameMapType{}
  783. req := requestWithBody(method, path, body)
  784. if method == "POST" {
  785. req.Header.Add("Content-Type", MIMEPOSTForm)
  786. }
  787. err := b.Bind(req, &obj)
  788. assert.Error(t, err)
  789. obj = InvalidNameMapType{}
  790. req = requestWithBody(method, badPath, badBody)
  791. err = JSON.Bind(req, &obj)
  792. assert.Error(t, err)
  793. }
  794. func testFormBindingForType(t *testing.T, method, path, badPath, body, badBody string, typ string) {
  795. b := Form
  796. assert.Equal(t, "form", b.Name())
  797. req := requestWithBody(method, path, body)
  798. if method == "POST" {
  799. req.Header.Add("Content-Type", MIMEPOSTForm)
  800. }
  801. switch typ {
  802. case "Slice":
  803. obj := FooStructForSliceType{}
  804. err := b.Bind(req, &obj)
  805. assert.NoError(t, err)
  806. assert.Equal(t, []int{1, 2}, obj.SliceFoo)
  807. obj = FooStructForSliceType{}
  808. req = requestWithBody(method, badPath, badBody)
  809. err = JSON.Bind(req, &obj)
  810. assert.Error(t, err)
  811. case "Struct":
  812. obj := FooStructForStructType{}
  813. err := b.Bind(req, &obj)
  814. assert.NoError(t, err)
  815. assert.Equal(t,
  816. struct {
  817. Idx int "form:\"idx\""
  818. }(struct {
  819. Idx int "form:\"idx\""
  820. }{Idx: 123}),
  821. obj.StructFoo)
  822. case "StructPointer":
  823. obj := FooStructForStructPointerType{}
  824. err := b.Bind(req, &obj)
  825. assert.NoError(t, err)
  826. assert.Equal(t,
  827. struct {
  828. Name string "form:\"name\""
  829. }(struct {
  830. Name string "form:\"name\""
  831. }{Name: "thinkerou"}),
  832. *obj.StructPointerFoo)
  833. case "Map":
  834. obj := FooStructForMapType{}
  835. err := b.Bind(req, &obj)
  836. assert.NoError(t, err)
  837. assert.Equal(t, float64(123), obj.MapFoo["bar"].(float64))
  838. case "SliceMap":
  839. obj := FooStructForSliceMapType{}
  840. err := b.Bind(req, &obj)
  841. assert.Error(t, err)
  842. case "Ptr":
  843. obj := FooStructForStringPtrType{}
  844. err := b.Bind(req, &obj)
  845. assert.NoError(t, err)
  846. assert.Nil(t, obj.PtrFoo)
  847. assert.Equal(t, "test", *obj.PtrBar)
  848. obj = FooStructForStringPtrType{}
  849. obj.PtrBar = new(string)
  850. err = b.Bind(req, &obj)
  851. assert.NoError(t, err)
  852. assert.Equal(t, "test", *obj.PtrBar)
  853. objErr := FooStructForMapPtrType{}
  854. err = b.Bind(req, &objErr)
  855. assert.Error(t, err)
  856. obj = FooStructForStringPtrType{}
  857. req = requestWithBody(method, badPath, badBody)
  858. err = b.Bind(req, &obj)
  859. assert.Error(t, err)
  860. }
  861. }
  862. func testQueryBinding(t *testing.T, method, path, badPath, body, badBody string) {
  863. b := Query
  864. assert.Equal(t, "query", b.Name())
  865. obj := FooBarStruct{}
  866. req := requestWithBody(method, path, body)
  867. if method == "POST" {
  868. req.Header.Add("Content-Type", MIMEPOSTForm)
  869. }
  870. err := b.Bind(req, &obj)
  871. assert.NoError(t, err)
  872. assert.Equal(t, "bar", obj.Foo)
  873. assert.Equal(t, "foo", obj.Bar)
  874. }
  875. func testQueryBindingFail(t *testing.T, method, path, badPath, body, badBody string) {
  876. b := Query
  877. assert.Equal(t, "query", b.Name())
  878. obj := FooStructForMapType{}
  879. req := requestWithBody(method, path, body)
  880. if method == "POST" {
  881. req.Header.Add("Content-Type", MIMEPOSTForm)
  882. }
  883. err := b.Bind(req, &obj)
  884. assert.Error(t, err)
  885. }
  886. func testQueryBindingBoolFail(t *testing.T, method, path, badPath, body, badBody string) {
  887. b := Query
  888. assert.Equal(t, "query", b.Name())
  889. obj := FooStructForBoolType{}
  890. req := requestWithBody(method, path, body)
  891. if method == "POST" {
  892. req.Header.Add("Content-Type", MIMEPOSTForm)
  893. }
  894. err := b.Bind(req, &obj)
  895. assert.Error(t, err)
  896. }
  897. func testBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  898. assert.Equal(t, name, b.Name())
  899. obj := FooStruct{}
  900. req := requestWithBody("POST", path, body)
  901. err := b.Bind(req, &obj)
  902. assert.NoError(t, err)
  903. assert.Equal(t, "bar", obj.Foo)
  904. obj = FooStruct{}
  905. req = requestWithBody("POST", badPath, badBody)
  906. err = JSON.Bind(req, &obj)
  907. assert.Error(t, err)
  908. }
  909. func testBodyBindingUseNumber(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  910. assert.Equal(t, name, b.Name())
  911. obj := FooStructUseNumber{}
  912. req := requestWithBody("POST", path, body)
  913. EnableDecoderUseNumber = true
  914. err := b.Bind(req, &obj)
  915. assert.NoError(t, err)
  916. // we hope it is int64(123)
  917. v, e := obj.Foo.(json.Number).Int64()
  918. assert.NoError(t, e)
  919. assert.Equal(t, int64(123), v)
  920. obj = FooStructUseNumber{}
  921. req = requestWithBody("POST", badPath, badBody)
  922. err = JSON.Bind(req, &obj)
  923. assert.Error(t, err)
  924. }
  925. func testBodyBindingUseNumber2(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  926. assert.Equal(t, name, b.Name())
  927. obj := FooStructUseNumber{}
  928. req := requestWithBody("POST", path, body)
  929. EnableDecoderUseNumber = false
  930. err := b.Bind(req, &obj)
  931. assert.NoError(t, err)
  932. // it will return float64(123) if not use EnableDecoderUseNumber
  933. // maybe it is not hoped
  934. assert.Equal(t, float64(123), obj.Foo)
  935. obj = FooStructUseNumber{}
  936. req = requestWithBody("POST", badPath, badBody)
  937. err = JSON.Bind(req, &obj)
  938. assert.Error(t, err)
  939. }
  940. func testBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  941. assert.Equal(t, name, b.Name())
  942. obj := FooStruct{}
  943. req := requestWithBody("POST", path, body)
  944. err := b.Bind(req, &obj)
  945. assert.Error(t, err)
  946. assert.Equal(t, "", obj.Foo)
  947. obj = FooStruct{}
  948. req = requestWithBody("POST", badPath, badBody)
  949. err = JSON.Bind(req, &obj)
  950. assert.Error(t, err)
  951. }
  952. func testProtoBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  953. assert.Equal(t, name, b.Name())
  954. obj := protoexample.Test{}
  955. req := requestWithBody("POST", path, body)
  956. req.Header.Add("Content-Type", MIMEPROTOBUF)
  957. err := b.Bind(req, &obj)
  958. assert.NoError(t, err)
  959. assert.Equal(t, "yes", *obj.Label)
  960. obj = protoexample.Test{}
  961. req = requestWithBody("POST", badPath, badBody)
  962. req.Header.Add("Content-Type", MIMEPROTOBUF)
  963. err = ProtoBuf.Bind(req, &obj)
  964. assert.Error(t, err)
  965. }
  966. type hook struct{}
  967. func (h hook) Read([]byte) (int, error) {
  968. return 0, errors.New("error")
  969. }
  970. func testProtoBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  971. assert.Equal(t, name, b.Name())
  972. obj := protoexample.Test{}
  973. req := requestWithBody("POST", path, body)
  974. req.Body = ioutil.NopCloser(&hook{})
  975. req.Header.Add("Content-Type", MIMEPROTOBUF)
  976. err := b.Bind(req, &obj)
  977. assert.Error(t, err)
  978. obj = protoexample.Test{}
  979. req = requestWithBody("POST", badPath, badBody)
  980. req.Header.Add("Content-Type", MIMEPROTOBUF)
  981. err = ProtoBuf.Bind(req, &obj)
  982. assert.Error(t, err)
  983. }
  984. func testMsgPackBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  985. assert.Equal(t, name, b.Name())
  986. obj := FooStruct{}
  987. req := requestWithBody("POST", path, body)
  988. req.Header.Add("Content-Type", MIMEMSGPACK)
  989. err := b.Bind(req, &obj)
  990. assert.NoError(t, err)
  991. assert.Equal(t, "bar", obj.Foo)
  992. obj = FooStruct{}
  993. req = requestWithBody("POST", badPath, badBody)
  994. req.Header.Add("Content-Type", MIMEMSGPACK)
  995. err = MsgPack.Bind(req, &obj)
  996. assert.Error(t, err)
  997. }
  998. func requestWithBody(method, path, body string) (req *http.Request) {
  999. req, _ = http.NewRequest(method, path, bytes.NewBufferString(body))
  1000. return
  1001. }