binding_test.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  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 FooStruct struct {
  24. Foo string `msgpack:"foo" json:"foo" form:"foo" xml:"foo" binding:"required"`
  25. }
  26. type FooBarStruct struct {
  27. FooStruct
  28. Bar string `msgpack:"bar" json:"bar" form:"bar" xml:"bar" binding:"required"`
  29. }
  30. type FooBarFileStruct struct {
  31. FooBarStruct
  32. File *multipart.FileHeader `form:"file" binding:"required"`
  33. }
  34. type FooBarFileFailStruct struct {
  35. FooBarStruct
  36. File *multipart.FileHeader `invalid_name:"file" binding:"required"`
  37. // for unexport test
  38. data *multipart.FileHeader `form:"data" binding:"required"`
  39. }
  40. type FooDefaultBarStruct struct {
  41. FooStruct
  42. Bar string `msgpack:"bar" json:"bar" form:"bar,default=hello" xml:"bar" binding:"required"`
  43. }
  44. type FooStructUseNumber struct {
  45. Foo interface{} `json:"foo" binding:"required"`
  46. }
  47. type FooBarStructForTimeType struct {
  48. TimeFoo time.Time `form:"time_foo" time_format:"2006-01-02" time_utc:"1" time_location:"Asia/Chongqing"`
  49. TimeBar time.Time `form:"time_bar" time_format:"2006-01-02" time_utc:"1"`
  50. }
  51. type FooStructForTimeTypeNotFormat struct {
  52. TimeFoo time.Time `form:"time_foo"`
  53. }
  54. type FooStructForTimeTypeFailFormat struct {
  55. TimeFoo time.Time `form:"time_foo" time_format:"2017-11-15"`
  56. }
  57. type FooStructForTimeTypeFailLocation struct {
  58. TimeFoo time.Time `form:"time_foo" time_format:"2006-01-02" time_location:"/asia/chongqing"`
  59. }
  60. type FooStructForMapType struct {
  61. MapFoo map[string]interface{} `form:"map_foo"`
  62. }
  63. type FooStructForIgnoreFormTag struct {
  64. Foo *string `form:"-"`
  65. }
  66. type InvalidNameType struct {
  67. TestName string `invalid_name:"test_name"`
  68. }
  69. type InvalidNameMapType struct {
  70. TestName struct {
  71. MapFoo map[string]interface{} `form:"map_foo"`
  72. }
  73. }
  74. type FooStructForSliceType struct {
  75. SliceFoo []int `form:"slice_foo"`
  76. }
  77. type FooStructForStructType struct {
  78. StructFoo struct {
  79. Idx int `form:"idx"`
  80. }
  81. }
  82. type FooStructForStructPointerType struct {
  83. StructPointerFoo *struct {
  84. Name string `form:"name"`
  85. }
  86. }
  87. type FooStructForSliceMapType struct {
  88. // Unknown type: not support map
  89. SliceMapFoo []map[string]interface{} `form:"slice_map_foo"`
  90. }
  91. type FooStructForBoolType struct {
  92. BoolFoo bool `form:"bool_foo"`
  93. }
  94. type FooBarStructForIntType struct {
  95. IntFoo int `form:"int_foo"`
  96. IntBar int `form:"int_bar" binding:"required"`
  97. }
  98. type FooBarStructForInt8Type struct {
  99. Int8Foo int8 `form:"int8_foo"`
  100. Int8Bar int8 `form:"int8_bar" binding:"required"`
  101. }
  102. type FooBarStructForInt16Type struct {
  103. Int16Foo int16 `form:"int16_foo"`
  104. Int16Bar int16 `form:"int16_bar" binding:"required"`
  105. }
  106. type FooBarStructForInt32Type struct {
  107. Int32Foo int32 `form:"int32_foo"`
  108. Int32Bar int32 `form:"int32_bar" binding:"required"`
  109. }
  110. type FooBarStructForInt64Type struct {
  111. Int64Foo int64 `form:"int64_foo"`
  112. Int64Bar int64 `form:"int64_bar" binding:"required"`
  113. }
  114. type FooBarStructForUintType struct {
  115. UintFoo uint `form:"uint_foo"`
  116. UintBar uint `form:"uint_bar" binding:"required"`
  117. }
  118. type FooBarStructForUint8Type struct {
  119. Uint8Foo uint8 `form:"uint8_foo"`
  120. Uint8Bar uint8 `form:"uint8_bar" binding:"required"`
  121. }
  122. type FooBarStructForUint16Type struct {
  123. Uint16Foo uint16 `form:"uint16_foo"`
  124. Uint16Bar uint16 `form:"uint16_bar" binding:"required"`
  125. }
  126. type FooBarStructForUint32Type struct {
  127. Uint32Foo uint32 `form:"uint32_foo"`
  128. Uint32Bar uint32 `form:"uint32_bar" binding:"required"`
  129. }
  130. type FooBarStructForUint64Type struct {
  131. Uint64Foo uint64 `form:"uint64_foo"`
  132. Uint64Bar uint64 `form:"uint64_bar" binding:"required"`
  133. }
  134. type FooBarStructForBoolType struct {
  135. BoolFoo bool `form:"bool_foo"`
  136. BoolBar bool `form:"bool_bar" binding:"required"`
  137. }
  138. type FooBarStructForFloat32Type struct {
  139. Float32Foo float32 `form:"float32_foo"`
  140. Float32Bar float32 `form:"float32_bar" binding:"required"`
  141. }
  142. type FooBarStructForFloat64Type struct {
  143. Float64Foo float64 `form:"float64_foo"`
  144. Float64Bar float64 `form:"float64_bar" binding:"required"`
  145. }
  146. type FooStructForStringPtrType struct {
  147. PtrFoo *string `form:"ptr_foo"`
  148. PtrBar *string `form:"ptr_bar" binding:"required"`
  149. }
  150. type FooStructForMapPtrType struct {
  151. PtrBar *map[string]interface{} `form:"ptr_bar"`
  152. }
  153. func TestBindingDefault(t *testing.T) {
  154. assert.Equal(t, Form, Default("GET", ""))
  155. assert.Equal(t, Form, Default("GET", MIMEJSON))
  156. assert.Equal(t, JSON, Default("POST", MIMEJSON))
  157. assert.Equal(t, JSON, Default("PUT", MIMEJSON))
  158. assert.Equal(t, XML, Default("POST", MIMEXML))
  159. assert.Equal(t, XML, Default("PUT", MIMEXML2))
  160. assert.Equal(t, Form, Default("POST", MIMEPOSTForm))
  161. assert.Equal(t, Form, Default("PUT", MIMEPOSTForm))
  162. assert.Equal(t, FormMultipart, Default("POST", MIMEMultipartPOSTForm))
  163. assert.Equal(t, FormMultipart, Default("PUT", MIMEMultipartPOSTForm))
  164. assert.Equal(t, ProtoBuf, Default("POST", MIMEPROTOBUF))
  165. assert.Equal(t, ProtoBuf, Default("PUT", MIMEPROTOBUF))
  166. assert.Equal(t, MsgPack, Default("POST", MIMEMSGPACK))
  167. assert.Equal(t, MsgPack, Default("PUT", MIMEMSGPACK2))
  168. assert.Equal(t, YAML, Default("POST", MIMEYAML))
  169. assert.Equal(t, YAML, Default("PUT", MIMEYAML))
  170. }
  171. func TestBindingJSONNilBody(t *testing.T) {
  172. var obj FooStruct
  173. req, _ := http.NewRequest(http.MethodPost, "/", nil)
  174. err := JSON.Bind(req, &obj)
  175. assert.Error(t, err)
  176. }
  177. func TestBindingJSON(t *testing.T) {
  178. testBodyBinding(t,
  179. JSON, "json",
  180. "/", "/",
  181. `{"foo": "bar"}`, `{"bar": "foo"}`)
  182. }
  183. func TestBindingJSONUseNumber(t *testing.T) {
  184. testBodyBindingUseNumber(t,
  185. JSON, "json",
  186. "/", "/",
  187. `{"foo": 123}`, `{"bar": "foo"}`)
  188. }
  189. func TestBindingJSONUseNumber2(t *testing.T) {
  190. testBodyBindingUseNumber2(t,
  191. JSON, "json",
  192. "/", "/",
  193. `{"foo": 123}`, `{"bar": "foo"}`)
  194. }
  195. func TestBindingForm(t *testing.T) {
  196. testFormBinding(t, "POST",
  197. "/", "/",
  198. "foo=bar&bar=foo", "bar2=foo")
  199. }
  200. func TestBindingForm2(t *testing.T) {
  201. testFormBinding(t, "GET",
  202. "/?foo=bar&bar=foo", "/?bar2=foo",
  203. "", "")
  204. }
  205. func TestBindingFormDefaultValue(t *testing.T) {
  206. testFormBindingDefaultValue(t, "POST",
  207. "/", "/",
  208. "foo=bar", "bar2=foo")
  209. }
  210. func TestBindingFormDefaultValue2(t *testing.T) {
  211. testFormBindingDefaultValue(t, "GET",
  212. "/?foo=bar", "/?bar2=foo",
  213. "", "")
  214. }
  215. func TestBindingFormForTime(t *testing.T) {
  216. testFormBindingForTime(t, "POST",
  217. "/", "/",
  218. "time_foo=2017-11-15&time_bar=", "bar2=foo")
  219. testFormBindingForTimeNotFormat(t, "POST",
  220. "/", "/",
  221. "time_foo=2017-11-15", "bar2=foo")
  222. testFormBindingForTimeFailFormat(t, "POST",
  223. "/", "/",
  224. "time_foo=2017-11-15", "bar2=foo")
  225. testFormBindingForTimeFailLocation(t, "POST",
  226. "/", "/",
  227. "time_foo=2017-11-15", "bar2=foo")
  228. }
  229. func TestBindingFormForTime2(t *testing.T) {
  230. testFormBindingForTime(t, "GET",
  231. "/?time_foo=2017-11-15&time_bar=", "/?bar2=foo",
  232. "", "")
  233. testFormBindingForTimeNotFormat(t, "GET",
  234. "/?time_foo=2017-11-15", "/?bar2=foo",
  235. "", "")
  236. testFormBindingForTimeFailFormat(t, "GET",
  237. "/?time_foo=2017-11-15", "/?bar2=foo",
  238. "", "")
  239. testFormBindingForTimeFailLocation(t, "GET",
  240. "/?time_foo=2017-11-15", "/?bar2=foo",
  241. "", "")
  242. }
  243. func TestFormBindingIgnoreField(t *testing.T) {
  244. testFormBindingIgnoreField(t, "POST",
  245. "/", "/",
  246. "-=bar", "")
  247. }
  248. func TestBindingFormInvalidName(t *testing.T) {
  249. testFormBindingInvalidName(t, "POST",
  250. "/", "/",
  251. "test_name=bar", "bar2=foo")
  252. }
  253. func TestBindingFormInvalidName2(t *testing.T) {
  254. testFormBindingInvalidName2(t, "POST",
  255. "/", "/",
  256. "map_foo=bar", "bar2=foo")
  257. }
  258. func TestBindingFormForType(t *testing.T) {
  259. testFormBindingForType(t, "POST",
  260. "/", "/",
  261. "map_foo={\"bar\":123}", "map_foo=1", "Map")
  262. testFormBindingForType(t, "POST",
  263. "/", "/",
  264. "slice_foo=1&slice_foo=2", "bar2=1&bar2=2", "Slice")
  265. testFormBindingForType(t, "GET",
  266. "/?slice_foo=1&slice_foo=2", "/?bar2=1&bar2=2",
  267. "", "", "Slice")
  268. testFormBindingForType(t, "POST",
  269. "/", "/",
  270. "slice_map_foo=1&slice_map_foo=2", "bar2=1&bar2=2", "SliceMap")
  271. testFormBindingForType(t, "GET",
  272. "/?slice_map_foo=1&slice_map_foo=2", "/?bar2=1&bar2=2",
  273. "", "", "SliceMap")
  274. testFormBindingForType(t, "POST",
  275. "/", "/",
  276. "int_foo=&int_bar=-12", "bar2=-123", "Int")
  277. testFormBindingForType(t, "GET",
  278. "/?int_foo=&int_bar=-12", "/?bar2=-123",
  279. "", "", "Int")
  280. testFormBindingForType(t, "POST",
  281. "/", "/",
  282. "int8_foo=&int8_bar=-12", "bar2=-123", "Int8")
  283. testFormBindingForType(t, "GET",
  284. "/?int8_foo=&int8_bar=-12", "/?bar2=-123",
  285. "", "", "Int8")
  286. testFormBindingForType(t, "POST",
  287. "/", "/",
  288. "int16_foo=&int16_bar=-12", "bar2=-123", "Int16")
  289. testFormBindingForType(t, "GET",
  290. "/?int16_foo=&int16_bar=-12", "/?bar2=-123",
  291. "", "", "Int16")
  292. testFormBindingForType(t, "POST",
  293. "/", "/",
  294. "int32_foo=&int32_bar=-12", "bar2=-123", "Int32")
  295. testFormBindingForType(t, "GET",
  296. "/?int32_foo=&int32_bar=-12", "/?bar2=-123",
  297. "", "", "Int32")
  298. testFormBindingForType(t, "POST",
  299. "/", "/",
  300. "int64_foo=&int64_bar=-12", "bar2=-123", "Int64")
  301. testFormBindingForType(t, "GET",
  302. "/?int64_foo=&int64_bar=-12", "/?bar2=-123",
  303. "", "", "Int64")
  304. testFormBindingForType(t, "POST",
  305. "/", "/",
  306. "uint_foo=&uint_bar=12", "bar2=123", "Uint")
  307. testFormBindingForType(t, "GET",
  308. "/?uint_foo=&uint_bar=12", "/?bar2=123",
  309. "", "", "Uint")
  310. testFormBindingForType(t, "POST",
  311. "/", "/",
  312. "uint8_foo=&uint8_bar=12", "bar2=123", "Uint8")
  313. testFormBindingForType(t, "GET",
  314. "/?uint8_foo=&uint8_bar=12", "/?bar2=123",
  315. "", "", "Uint8")
  316. testFormBindingForType(t, "POST",
  317. "/", "/",
  318. "uint16_foo=&uint16_bar=12", "bar2=123", "Uint16")
  319. testFormBindingForType(t, "GET",
  320. "/?uint16_foo=&uint16_bar=12", "/?bar2=123",
  321. "", "", "Uint16")
  322. testFormBindingForType(t, "POST",
  323. "/", "/",
  324. "uint32_foo=&uint32_bar=12", "bar2=123", "Uint32")
  325. testFormBindingForType(t, "GET",
  326. "/?uint32_foo=&uint32_bar=12", "/?bar2=123",
  327. "", "", "Uint32")
  328. testFormBindingForType(t, "POST",
  329. "/", "/",
  330. "uint64_foo=&uint64_bar=12", "bar2=123", "Uint64")
  331. testFormBindingForType(t, "GET",
  332. "/?uint64_foo=&uint64_bar=12", "/?bar2=123",
  333. "", "", "Uint64")
  334. testFormBindingForType(t, "POST",
  335. "/", "/",
  336. "bool_foo=&bool_bar=true", "bar2=true", "Bool")
  337. testFormBindingForType(t, "GET",
  338. "/?bool_foo=&bool_bar=true", "/?bar2=true",
  339. "", "", "Bool")
  340. testFormBindingForType(t, "POST",
  341. "/", "/",
  342. "float32_foo=&float32_bar=-12.34", "bar2=12.3", "Float32")
  343. testFormBindingForType(t, "GET",
  344. "/?float32_foo=&float32_bar=-12.34", "/?bar2=12.3",
  345. "", "", "Float32")
  346. testFormBindingForType(t, "POST",
  347. "/", "/",
  348. "float64_foo=&float64_bar=-12.34", "bar2=12.3", "Float64")
  349. testFormBindingForType(t, "GET",
  350. "/?float64_foo=&float64_bar=-12.34", "/?bar2=12.3",
  351. "", "", "Float64")
  352. testFormBindingForType(t, "POST",
  353. "/", "/",
  354. "ptr_bar=test", "bar2=test", "Ptr")
  355. testFormBindingForType(t, "GET",
  356. "/?ptr_bar=test", "/?bar2=test",
  357. "", "", "Ptr")
  358. testFormBindingForType(t, "POST",
  359. "/", "/",
  360. "idx=123", "id1=1", "Struct")
  361. testFormBindingForType(t, "GET",
  362. "/?idx=123", "/?id1=1",
  363. "", "", "Struct")
  364. testFormBindingForType(t, "POST",
  365. "/", "/",
  366. "name=thinkerou", "name1=ou", "StructPointer")
  367. testFormBindingForType(t, "GET",
  368. "/?name=thinkerou", "/?name1=ou",
  369. "", "", "StructPointer")
  370. }
  371. func TestBindingQuery(t *testing.T) {
  372. testQueryBinding(t, "POST",
  373. "/?foo=bar&bar=foo", "/",
  374. "foo=unused", "bar2=foo")
  375. }
  376. func TestBindingQuery2(t *testing.T) {
  377. testQueryBinding(t, "GET",
  378. "/?foo=bar&bar=foo", "/?bar2=foo",
  379. "foo=unused", "")
  380. }
  381. func TestBindingQueryFail(t *testing.T) {
  382. testQueryBindingFail(t, "POST",
  383. "/?map_foo=", "/",
  384. "map_foo=unused", "bar2=foo")
  385. }
  386. func TestBindingQueryFail2(t *testing.T) {
  387. testQueryBindingFail(t, "GET",
  388. "/?map_foo=", "/?bar2=foo",
  389. "map_foo=unused", "")
  390. }
  391. func TestBindingQueryBoolFail(t *testing.T) {
  392. testQueryBindingBoolFail(t, "GET",
  393. "/?bool_foo=fasl", "/?bar2=foo",
  394. "bool_foo=unused", "")
  395. }
  396. func TestBindingXML(t *testing.T) {
  397. testBodyBinding(t,
  398. XML, "xml",
  399. "/", "/",
  400. "<map><foo>bar</foo></map>", "<map><bar>foo</bar></map>")
  401. }
  402. func TestBindingXMLFail(t *testing.T) {
  403. testBodyBindingFail(t,
  404. XML, "xml",
  405. "/", "/",
  406. "<map><foo>bar<foo></map>", "<map><bar>foo</bar></map>")
  407. }
  408. func TestBindingYAML(t *testing.T) {
  409. testBodyBinding(t,
  410. YAML, "yaml",
  411. "/", "/",
  412. `foo: bar`, `bar: foo`)
  413. }
  414. func TestBindingYAMLFail(t *testing.T) {
  415. testBodyBindingFail(t,
  416. YAML, "yaml",
  417. "/", "/",
  418. `foo:\nbar`, `bar: foo`)
  419. }
  420. func createFormPostRequest(t *testing.T) *http.Request {
  421. req, err := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", bytes.NewBufferString("foo=bar&bar=foo"))
  422. assert.NoError(t, err)
  423. req.Header.Set("Content-Type", MIMEPOSTForm)
  424. return req
  425. }
  426. func createDefaultFormPostRequest(t *testing.T) *http.Request {
  427. req, err := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", bytes.NewBufferString("foo=bar"))
  428. assert.NoError(t, err)
  429. req.Header.Set("Content-Type", MIMEPOSTForm)
  430. return req
  431. }
  432. func createFormPostRequestForMap(t *testing.T) *http.Request {
  433. req, err := http.NewRequest("POST", "/?map_foo=getfoo", bytes.NewBufferString("map_foo={\"bar\":123}"))
  434. assert.NoError(t, err)
  435. req.Header.Set("Content-Type", MIMEPOSTForm)
  436. return req
  437. }
  438. func createFormPostRequestForMapFail(t *testing.T) *http.Request {
  439. req, err := http.NewRequest("POST", "/?map_foo=getfoo", bytes.NewBufferString("map_foo=hello"))
  440. assert.NoError(t, err)
  441. req.Header.Set("Content-Type", MIMEPOSTForm)
  442. return req
  443. }
  444. func createFormFilesMultipartRequest(t *testing.T) *http.Request {
  445. boundary := "--testboundary"
  446. body := new(bytes.Buffer)
  447. mw := multipart.NewWriter(body)
  448. defer mw.Close()
  449. assert.NoError(t, mw.SetBoundary(boundary))
  450. assert.NoError(t, mw.WriteField("foo", "bar"))
  451. assert.NoError(t, mw.WriteField("bar", "foo"))
  452. f, err := os.Open("form.go")
  453. assert.NoError(t, err)
  454. defer f.Close()
  455. fw, err1 := mw.CreateFormFile("file", "form.go")
  456. assert.NoError(t, err1)
  457. io.Copy(fw, f)
  458. req, err2 := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", body)
  459. assert.NoError(t, err2)
  460. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  461. return req
  462. }
  463. func createFormFilesMultipartRequestFail(t *testing.T) *http.Request {
  464. boundary := "--testboundary"
  465. body := new(bytes.Buffer)
  466. mw := multipart.NewWriter(body)
  467. defer mw.Close()
  468. assert.NoError(t, mw.SetBoundary(boundary))
  469. assert.NoError(t, mw.WriteField("foo", "bar"))
  470. assert.NoError(t, mw.WriteField("bar", "foo"))
  471. f, err := os.Open("form.go")
  472. assert.NoError(t, err)
  473. defer f.Close()
  474. fw, err1 := mw.CreateFormFile("file_foo", "form_foo.go")
  475. assert.NoError(t, err1)
  476. io.Copy(fw, f)
  477. req, err2 := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", body)
  478. assert.NoError(t, err2)
  479. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  480. return req
  481. }
  482. func createFormMultipartRequest(t *testing.T) *http.Request {
  483. boundary := "--testboundary"
  484. body := new(bytes.Buffer)
  485. mw := multipart.NewWriter(body)
  486. defer mw.Close()
  487. assert.NoError(t, mw.SetBoundary(boundary))
  488. assert.NoError(t, mw.WriteField("foo", "bar"))
  489. assert.NoError(t, mw.WriteField("bar", "foo"))
  490. req, err := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", body)
  491. assert.NoError(t, err)
  492. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  493. return req
  494. }
  495. func createFormMultipartRequestForMap(t *testing.T) *http.Request {
  496. boundary := "--testboundary"
  497. body := new(bytes.Buffer)
  498. mw := multipart.NewWriter(body)
  499. defer mw.Close()
  500. assert.NoError(t, mw.SetBoundary(boundary))
  501. assert.NoError(t, mw.WriteField("map_foo", "{\"bar\":123, \"name\":\"thinkerou\", \"pai\": 3.14}"))
  502. req, err := http.NewRequest("POST", "/?map_foo=getfoo", body)
  503. assert.NoError(t, err)
  504. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  505. return req
  506. }
  507. func createFormMultipartRequestForMapFail(t *testing.T) *http.Request {
  508. boundary := "--testboundary"
  509. body := new(bytes.Buffer)
  510. mw := multipart.NewWriter(body)
  511. defer mw.Close()
  512. assert.NoError(t, mw.SetBoundary(boundary))
  513. assert.NoError(t, mw.WriteField("map_foo", "3.14"))
  514. req, err := http.NewRequest("POST", "/?map_foo=getfoo", body)
  515. assert.NoError(t, err)
  516. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  517. return req
  518. }
  519. func TestBindingFormPost(t *testing.T) {
  520. req := createFormPostRequest(t)
  521. var obj FooBarStruct
  522. assert.NoError(t, FormPost.Bind(req, &obj))
  523. assert.Equal(t, "form-urlencoded", FormPost.Name())
  524. assert.Equal(t, "bar", obj.Foo)
  525. assert.Equal(t, "foo", obj.Bar)
  526. }
  527. func TestBindingDefaultValueFormPost(t *testing.T) {
  528. req := createDefaultFormPostRequest(t)
  529. var obj FooDefaultBarStruct
  530. assert.NoError(t, FormPost.Bind(req, &obj))
  531. assert.Equal(t, "bar", obj.Foo)
  532. assert.Equal(t, "hello", obj.Bar)
  533. }
  534. func TestBindingFormPostForMap(t *testing.T) {
  535. req := createFormPostRequestForMap(t)
  536. var obj FooStructForMapType
  537. err := FormPost.Bind(req, &obj)
  538. assert.NoError(t, err)
  539. assert.Equal(t, float64(123), obj.MapFoo["bar"].(float64))
  540. }
  541. func TestBindingFormPostForMapFail(t *testing.T) {
  542. req := createFormPostRequestForMapFail(t)
  543. var obj FooStructForMapType
  544. err := FormPost.Bind(req, &obj)
  545. assert.Error(t, err)
  546. }
  547. func TestBindingFormFilesMultipart(t *testing.T) {
  548. req := createFormFilesMultipartRequest(t)
  549. var obj FooBarFileStruct
  550. FormMultipart.Bind(req, &obj)
  551. // file from os
  552. f, _ := os.Open("form.go")
  553. defer f.Close()
  554. fileActual, _ := ioutil.ReadAll(f)
  555. // file from multipart
  556. mf, _ := obj.File.Open()
  557. defer mf.Close()
  558. fileExpect, _ := ioutil.ReadAll(mf)
  559. assert.Equal(t, FormMultipart.Name(), "multipart/form-data")
  560. assert.Equal(t, obj.Foo, "bar")
  561. assert.Equal(t, obj.Bar, "foo")
  562. assert.Equal(t, fileExpect, fileActual)
  563. }
  564. func TestBindingFormFilesMultipartFail(t *testing.T) {
  565. req := createFormFilesMultipartRequestFail(t)
  566. var obj FooBarFileFailStruct
  567. err := FormMultipart.Bind(req, &obj)
  568. assert.Error(t, err)
  569. }
  570. func TestBindingFormMultipart(t *testing.T) {
  571. req := createFormMultipartRequest(t)
  572. var obj FooBarStruct
  573. assert.NoError(t, FormMultipart.Bind(req, &obj))
  574. assert.Equal(t, "multipart/form-data", FormMultipart.Name())
  575. assert.Equal(t, "bar", obj.Foo)
  576. assert.Equal(t, "foo", obj.Bar)
  577. }
  578. func TestBindingFormMultipartForMap(t *testing.T) {
  579. req := createFormMultipartRequestForMap(t)
  580. var obj FooStructForMapType
  581. err := FormMultipart.Bind(req, &obj)
  582. assert.NoError(t, err)
  583. assert.Equal(t, float64(123), obj.MapFoo["bar"].(float64))
  584. assert.Equal(t, "thinkerou", obj.MapFoo["name"].(string))
  585. assert.Equal(t, float64(3.14), obj.MapFoo["pai"].(float64))
  586. }
  587. func TestBindingFormMultipartForMapFail(t *testing.T) {
  588. req := createFormMultipartRequestForMapFail(t)
  589. var obj FooStructForMapType
  590. err := FormMultipart.Bind(req, &obj)
  591. assert.Error(t, err)
  592. }
  593. func TestBindingProtoBuf(t *testing.T) {
  594. test := &protoexample.Test{
  595. Label: proto.String("yes"),
  596. }
  597. data, _ := proto.Marshal(test)
  598. testProtoBodyBinding(t,
  599. ProtoBuf, "protobuf",
  600. "/", "/",
  601. string(data), string(data[1:]))
  602. }
  603. func TestBindingProtoBufFail(t *testing.T) {
  604. test := &protoexample.Test{
  605. Label: proto.String("yes"),
  606. }
  607. data, _ := proto.Marshal(test)
  608. testProtoBodyBindingFail(t,
  609. ProtoBuf, "protobuf",
  610. "/", "/",
  611. string(data), string(data[1:]))
  612. }
  613. func TestBindingMsgPack(t *testing.T) {
  614. test := FooStruct{
  615. Foo: "bar",
  616. }
  617. h := new(codec.MsgpackHandle)
  618. assert.NotNil(t, h)
  619. buf := bytes.NewBuffer([]byte{})
  620. assert.NotNil(t, buf)
  621. err := codec.NewEncoder(buf, h).Encode(test)
  622. assert.NoError(t, err)
  623. data := buf.Bytes()
  624. testMsgPackBodyBinding(t,
  625. MsgPack, "msgpack",
  626. "/", "/",
  627. string(data), string(data[1:]))
  628. }
  629. func TestValidationFails(t *testing.T) {
  630. var obj FooStruct
  631. req := requestWithBody("POST", "/", `{"bar": "foo"}`)
  632. err := JSON.Bind(req, &obj)
  633. assert.Error(t, err)
  634. }
  635. func TestValidationDisabled(t *testing.T) {
  636. backup := Validator
  637. Validator = nil
  638. defer func() { Validator = backup }()
  639. var obj FooStruct
  640. req := requestWithBody("POST", "/", `{"bar": "foo"}`)
  641. err := JSON.Bind(req, &obj)
  642. assert.NoError(t, err)
  643. }
  644. func TestExistsSucceeds(t *testing.T) {
  645. type HogeStruct struct {
  646. Hoge *int `json:"hoge" binding:"exists"`
  647. }
  648. var obj HogeStruct
  649. req := requestWithBody("POST", "/", `{"hoge": 0}`)
  650. err := JSON.Bind(req, &obj)
  651. assert.NoError(t, err)
  652. }
  653. func TestExistsFails(t *testing.T) {
  654. type HogeStruct struct {
  655. Hoge *int `json:"foo" binding:"exists"`
  656. }
  657. var obj HogeStruct
  658. req := requestWithBody("POST", "/", `{"boen": 0}`)
  659. err := JSON.Bind(req, &obj)
  660. assert.Error(t, err)
  661. }
  662. func TestUriBinding(t *testing.T) {
  663. b := Uri
  664. assert.Equal(t, "uri", b.Name())
  665. type Tag struct {
  666. Name string `uri:"name"`
  667. }
  668. var tag Tag
  669. m := make(map[string][]string)
  670. m["name"] = []string{"thinkerou"}
  671. assert.NoError(t, b.BindUri(m, &tag))
  672. assert.Equal(t, "thinkerou", tag.Name)
  673. type NotSupportStruct struct {
  674. Name map[string]interface{} `uri:"name"`
  675. }
  676. var not NotSupportStruct
  677. assert.Error(t, b.BindUri(m, &not))
  678. assert.Equal(t, map[string]interface{}(nil), not.Name)
  679. }
  680. func TestUriInnerBinding(t *testing.T) {
  681. type Tag struct {
  682. Name string `uri:"name"`
  683. S struct {
  684. Age int `uri:"age"`
  685. }
  686. }
  687. expectedName := "mike"
  688. expectedAge := 25
  689. m := map[string][]string{
  690. "name": {expectedName},
  691. "age": {strconv.Itoa(expectedAge)},
  692. }
  693. var tag Tag
  694. assert.NoError(t, Uri.BindUri(m, &tag))
  695. assert.Equal(t, tag.Name, expectedName)
  696. assert.Equal(t, tag.S.Age, expectedAge)
  697. }
  698. func testFormBinding(t *testing.T, method, path, badPath, body, badBody string) {
  699. b := Form
  700. assert.Equal(t, "form", b.Name())
  701. obj := FooBarStruct{}
  702. req := requestWithBody(method, path, body)
  703. if method == "POST" {
  704. req.Header.Add("Content-Type", MIMEPOSTForm)
  705. }
  706. err := b.Bind(req, &obj)
  707. assert.NoError(t, err)
  708. assert.Equal(t, "bar", obj.Foo)
  709. assert.Equal(t, "foo", obj.Bar)
  710. obj = FooBarStruct{}
  711. req = requestWithBody(method, badPath, badBody)
  712. err = JSON.Bind(req, &obj)
  713. assert.Error(t, err)
  714. }
  715. func testFormBindingDefaultValue(t *testing.T, method, path, badPath, body, badBody string) {
  716. b := Form
  717. assert.Equal(t, "form", b.Name())
  718. obj := FooDefaultBarStruct{}
  719. req := requestWithBody(method, path, body)
  720. if method == "POST" {
  721. req.Header.Add("Content-Type", MIMEPOSTForm)
  722. }
  723. err := b.Bind(req, &obj)
  724. assert.NoError(t, err)
  725. assert.Equal(t, "bar", obj.Foo)
  726. assert.Equal(t, "hello", obj.Bar)
  727. obj = FooDefaultBarStruct{}
  728. req = requestWithBody(method, badPath, badBody)
  729. err = JSON.Bind(req, &obj)
  730. assert.Error(t, err)
  731. }
  732. func TestFormBindingFail(t *testing.T) {
  733. b := Form
  734. assert.Equal(t, "form", b.Name())
  735. obj := FooBarStruct{}
  736. req, _ := http.NewRequest("POST", "/", nil)
  737. err := b.Bind(req, &obj)
  738. assert.Error(t, err)
  739. }
  740. func TestFormBindingMultipartFail(t *testing.T) {
  741. obj := FooBarStruct{}
  742. req, err := http.NewRequest("POST", "/", strings.NewReader("foo=bar"))
  743. assert.NoError(t, err)
  744. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+";boundary=testboundary")
  745. _, err = req.MultipartReader()
  746. assert.NoError(t, err)
  747. err = Form.Bind(req, &obj)
  748. assert.Error(t, err)
  749. }
  750. func TestFormPostBindingFail(t *testing.T) {
  751. b := FormPost
  752. assert.Equal(t, "form-urlencoded", b.Name())
  753. obj := FooBarStruct{}
  754. req, _ := http.NewRequest("POST", "/", nil)
  755. err := b.Bind(req, &obj)
  756. assert.Error(t, err)
  757. }
  758. func TestFormMultipartBindingFail(t *testing.T) {
  759. b := FormMultipart
  760. assert.Equal(t, "multipart/form-data", b.Name())
  761. obj := FooBarStruct{}
  762. req, _ := http.NewRequest("POST", "/", nil)
  763. err := b.Bind(req, &obj)
  764. assert.Error(t, err)
  765. }
  766. func testFormBindingForTime(t *testing.T, method, path, badPath, body, badBody string) {
  767. b := Form
  768. assert.Equal(t, "form", b.Name())
  769. obj := FooBarStructForTimeType{}
  770. req := requestWithBody(method, path, body)
  771. if method == "POST" {
  772. req.Header.Add("Content-Type", MIMEPOSTForm)
  773. }
  774. err := b.Bind(req, &obj)
  775. assert.NoError(t, err)
  776. assert.Equal(t, int64(1510675200), obj.TimeFoo.Unix())
  777. assert.Equal(t, "Asia/Chongqing", obj.TimeFoo.Location().String())
  778. assert.Equal(t, int64(-62135596800), obj.TimeBar.Unix())
  779. assert.Equal(t, "UTC", obj.TimeBar.Location().String())
  780. obj = FooBarStructForTimeType{}
  781. req = requestWithBody(method, badPath, badBody)
  782. err = JSON.Bind(req, &obj)
  783. assert.Error(t, err)
  784. }
  785. func testFormBindingForTimeNotFormat(t *testing.T, method, path, badPath, body, badBody string) {
  786. b := Form
  787. assert.Equal(t, "form", b.Name())
  788. obj := FooStructForTimeTypeNotFormat{}
  789. req := requestWithBody(method, path, body)
  790. if method == "POST" {
  791. req.Header.Add("Content-Type", MIMEPOSTForm)
  792. }
  793. err := b.Bind(req, &obj)
  794. assert.Error(t, err)
  795. obj = FooStructForTimeTypeNotFormat{}
  796. req = requestWithBody(method, badPath, badBody)
  797. err = JSON.Bind(req, &obj)
  798. assert.Error(t, err)
  799. }
  800. func testFormBindingForTimeFailFormat(t *testing.T, method, path, badPath, body, badBody string) {
  801. b := Form
  802. assert.Equal(t, "form", b.Name())
  803. obj := FooStructForTimeTypeFailFormat{}
  804. req := requestWithBody(method, path, body)
  805. if method == "POST" {
  806. req.Header.Add("Content-Type", MIMEPOSTForm)
  807. }
  808. err := b.Bind(req, &obj)
  809. assert.Error(t, err)
  810. obj = FooStructForTimeTypeFailFormat{}
  811. req = requestWithBody(method, badPath, badBody)
  812. err = JSON.Bind(req, &obj)
  813. assert.Error(t, err)
  814. }
  815. func testFormBindingForTimeFailLocation(t *testing.T, method, path, badPath, body, badBody string) {
  816. b := Form
  817. assert.Equal(t, "form", b.Name())
  818. obj := FooStructForTimeTypeFailLocation{}
  819. req := requestWithBody(method, path, body)
  820. if method == "POST" {
  821. req.Header.Add("Content-Type", MIMEPOSTForm)
  822. }
  823. err := b.Bind(req, &obj)
  824. assert.Error(t, err)
  825. obj = FooStructForTimeTypeFailLocation{}
  826. req = requestWithBody(method, badPath, badBody)
  827. err = JSON.Bind(req, &obj)
  828. assert.Error(t, err)
  829. }
  830. func testFormBindingIgnoreField(t *testing.T, method, path, badPath, body, badBody string) {
  831. b := Form
  832. assert.Equal(t, "form", b.Name())
  833. obj := FooStructForIgnoreFormTag{}
  834. req := requestWithBody(method, path, body)
  835. if method == "POST" {
  836. req.Header.Add("Content-Type", MIMEPOSTForm)
  837. }
  838. err := b.Bind(req, &obj)
  839. assert.NoError(t, err)
  840. assert.Nil(t, obj.Foo)
  841. }
  842. func testFormBindingInvalidName(t *testing.T, method, path, badPath, body, badBody string) {
  843. b := Form
  844. assert.Equal(t, "form", b.Name())
  845. obj := InvalidNameType{}
  846. req := requestWithBody(method, path, body)
  847. if method == "POST" {
  848. req.Header.Add("Content-Type", MIMEPOSTForm)
  849. }
  850. err := b.Bind(req, &obj)
  851. assert.NoError(t, err)
  852. assert.Equal(t, "", obj.TestName)
  853. obj = InvalidNameType{}
  854. req = requestWithBody(method, badPath, badBody)
  855. err = JSON.Bind(req, &obj)
  856. assert.Error(t, err)
  857. }
  858. func testFormBindingInvalidName2(t *testing.T, method, path, badPath, body, badBody string) {
  859. b := Form
  860. assert.Equal(t, "form", b.Name())
  861. obj := InvalidNameMapType{}
  862. req := requestWithBody(method, path, body)
  863. if method == "POST" {
  864. req.Header.Add("Content-Type", MIMEPOSTForm)
  865. }
  866. err := b.Bind(req, &obj)
  867. assert.Error(t, err)
  868. obj = InvalidNameMapType{}
  869. req = requestWithBody(method, badPath, badBody)
  870. err = JSON.Bind(req, &obj)
  871. assert.Error(t, err)
  872. }
  873. func testFormBindingForType(t *testing.T, method, path, badPath, body, badBody string, typ string) {
  874. b := Form
  875. assert.Equal(t, "form", b.Name())
  876. req := requestWithBody(method, path, body)
  877. if method == "POST" {
  878. req.Header.Add("Content-Type", MIMEPOSTForm)
  879. }
  880. switch typ {
  881. case "Int":
  882. obj := FooBarStructForIntType{}
  883. err := b.Bind(req, &obj)
  884. assert.NoError(t, err)
  885. assert.Equal(t, int(0), obj.IntFoo)
  886. assert.Equal(t, int(-12), obj.IntBar)
  887. obj = FooBarStructForIntType{}
  888. req = requestWithBody(method, badPath, badBody)
  889. err = JSON.Bind(req, &obj)
  890. assert.Error(t, err)
  891. case "Int8":
  892. obj := FooBarStructForInt8Type{}
  893. err := b.Bind(req, &obj)
  894. assert.NoError(t, err)
  895. assert.Equal(t, int8(0), obj.Int8Foo)
  896. assert.Equal(t, int8(-12), obj.Int8Bar)
  897. obj = FooBarStructForInt8Type{}
  898. req = requestWithBody(method, badPath, badBody)
  899. err = JSON.Bind(req, &obj)
  900. assert.Error(t, err)
  901. case "Int16":
  902. obj := FooBarStructForInt16Type{}
  903. err := b.Bind(req, &obj)
  904. assert.NoError(t, err)
  905. assert.Equal(t, int16(0), obj.Int16Foo)
  906. assert.Equal(t, int16(-12), obj.Int16Bar)
  907. obj = FooBarStructForInt16Type{}
  908. req = requestWithBody(method, badPath, badBody)
  909. err = JSON.Bind(req, &obj)
  910. assert.Error(t, err)
  911. case "Int32":
  912. obj := FooBarStructForInt32Type{}
  913. err := b.Bind(req, &obj)
  914. assert.NoError(t, err)
  915. assert.Equal(t, int32(0), obj.Int32Foo)
  916. assert.Equal(t, int32(-12), obj.Int32Bar)
  917. obj = FooBarStructForInt32Type{}
  918. req = requestWithBody(method, badPath, badBody)
  919. err = JSON.Bind(req, &obj)
  920. assert.Error(t, err)
  921. case "Int64":
  922. obj := FooBarStructForInt64Type{}
  923. err := b.Bind(req, &obj)
  924. assert.NoError(t, err)
  925. assert.Equal(t, int64(0), obj.Int64Foo)
  926. assert.Equal(t, int64(-12), obj.Int64Bar)
  927. obj = FooBarStructForInt64Type{}
  928. req = requestWithBody(method, badPath, badBody)
  929. err = JSON.Bind(req, &obj)
  930. assert.Error(t, err)
  931. case "Uint":
  932. obj := FooBarStructForUintType{}
  933. err := b.Bind(req, &obj)
  934. assert.NoError(t, err)
  935. assert.Equal(t, uint(0x0), obj.UintFoo)
  936. assert.Equal(t, uint(0xc), obj.UintBar)
  937. obj = FooBarStructForUintType{}
  938. req = requestWithBody(method, badPath, badBody)
  939. err = JSON.Bind(req, &obj)
  940. assert.Error(t, err)
  941. case "Uint8":
  942. obj := FooBarStructForUint8Type{}
  943. err := b.Bind(req, &obj)
  944. assert.NoError(t, err)
  945. assert.Equal(t, uint8(0x0), obj.Uint8Foo)
  946. assert.Equal(t, uint8(0xc), obj.Uint8Bar)
  947. obj = FooBarStructForUint8Type{}
  948. req = requestWithBody(method, badPath, badBody)
  949. err = JSON.Bind(req, &obj)
  950. assert.Error(t, err)
  951. case "Uint16":
  952. obj := FooBarStructForUint16Type{}
  953. err := b.Bind(req, &obj)
  954. assert.NoError(t, err)
  955. assert.Equal(t, uint16(0x0), obj.Uint16Foo)
  956. assert.Equal(t, uint16(0xc), obj.Uint16Bar)
  957. obj = FooBarStructForUint16Type{}
  958. req = requestWithBody(method, badPath, badBody)
  959. err = JSON.Bind(req, &obj)
  960. assert.Error(t, err)
  961. case "Uint32":
  962. obj := FooBarStructForUint32Type{}
  963. err := b.Bind(req, &obj)
  964. assert.NoError(t, err)
  965. assert.Equal(t, uint32(0x0), obj.Uint32Foo)
  966. assert.Equal(t, uint32(0xc), obj.Uint32Bar)
  967. obj = FooBarStructForUint32Type{}
  968. req = requestWithBody(method, badPath, badBody)
  969. err = JSON.Bind(req, &obj)
  970. assert.Error(t, err)
  971. case "Uint64":
  972. obj := FooBarStructForUint64Type{}
  973. err := b.Bind(req, &obj)
  974. assert.NoError(t, err)
  975. assert.Equal(t, uint64(0x0), obj.Uint64Foo)
  976. assert.Equal(t, uint64(0xc), obj.Uint64Bar)
  977. obj = FooBarStructForUint64Type{}
  978. req = requestWithBody(method, badPath, badBody)
  979. err = JSON.Bind(req, &obj)
  980. assert.Error(t, err)
  981. case "Float32":
  982. obj := FooBarStructForFloat32Type{}
  983. err := b.Bind(req, &obj)
  984. assert.NoError(t, err)
  985. assert.Equal(t, float32(0.0), obj.Float32Foo)
  986. assert.Equal(t, float32(-12.34), obj.Float32Bar)
  987. obj = FooBarStructForFloat32Type{}
  988. req = requestWithBody(method, badPath, badBody)
  989. err = JSON.Bind(req, &obj)
  990. assert.Error(t, err)
  991. case "Float64":
  992. obj := FooBarStructForFloat64Type{}
  993. err := b.Bind(req, &obj)
  994. assert.NoError(t, err)
  995. assert.Equal(t, float64(0.0), obj.Float64Foo)
  996. assert.Equal(t, float64(-12.34), obj.Float64Bar)
  997. obj = FooBarStructForFloat64Type{}
  998. req = requestWithBody(method, badPath, badBody)
  999. err = JSON.Bind(req, &obj)
  1000. assert.Error(t, err)
  1001. case "Bool":
  1002. obj := FooBarStructForBoolType{}
  1003. err := b.Bind(req, &obj)
  1004. assert.NoError(t, err)
  1005. assert.False(t, obj.BoolFoo)
  1006. assert.True(t, obj.BoolBar)
  1007. obj = FooBarStructForBoolType{}
  1008. req = requestWithBody(method, badPath, badBody)
  1009. err = JSON.Bind(req, &obj)
  1010. assert.Error(t, err)
  1011. case "Slice":
  1012. obj := FooStructForSliceType{}
  1013. err := b.Bind(req, &obj)
  1014. assert.NoError(t, err)
  1015. assert.Equal(t, []int{1, 2}, obj.SliceFoo)
  1016. obj = FooStructForSliceType{}
  1017. req = requestWithBody(method, badPath, badBody)
  1018. err = JSON.Bind(req, &obj)
  1019. assert.Error(t, err)
  1020. case "Struct":
  1021. obj := FooStructForStructType{}
  1022. err := b.Bind(req, &obj)
  1023. assert.NoError(t, err)
  1024. assert.Equal(t,
  1025. struct {
  1026. Idx int "form:\"idx\""
  1027. }(struct {
  1028. Idx int "form:\"idx\""
  1029. }{Idx: 123}),
  1030. obj.StructFoo)
  1031. case "StructPointer":
  1032. obj := FooStructForStructPointerType{}
  1033. err := b.Bind(req, &obj)
  1034. assert.NoError(t, err)
  1035. assert.Equal(t,
  1036. struct {
  1037. Name string "form:\"name\""
  1038. }(struct {
  1039. Name string "form:\"name\""
  1040. }{Name: "thinkerou"}),
  1041. *obj.StructPointerFoo)
  1042. case "Map":
  1043. obj := FooStructForMapType{}
  1044. err := b.Bind(req, &obj)
  1045. assert.NoError(t, err)
  1046. assert.Equal(t, float64(123), obj.MapFoo["bar"].(float64))
  1047. case "SliceMap":
  1048. obj := FooStructForSliceMapType{}
  1049. err := b.Bind(req, &obj)
  1050. assert.Error(t, err)
  1051. case "Ptr":
  1052. obj := FooStructForStringPtrType{}
  1053. err := b.Bind(req, &obj)
  1054. assert.NoError(t, err)
  1055. assert.Nil(t, obj.PtrFoo)
  1056. assert.Equal(t, "test", *obj.PtrBar)
  1057. obj = FooStructForStringPtrType{}
  1058. obj.PtrBar = new(string)
  1059. err = b.Bind(req, &obj)
  1060. assert.NoError(t, err)
  1061. assert.Equal(t, "test", *obj.PtrBar)
  1062. objErr := FooStructForMapPtrType{}
  1063. err = b.Bind(req, &objErr)
  1064. assert.Error(t, err)
  1065. obj = FooStructForStringPtrType{}
  1066. req = requestWithBody(method, badPath, badBody)
  1067. err = b.Bind(req, &obj)
  1068. assert.Error(t, err)
  1069. }
  1070. }
  1071. func testQueryBinding(t *testing.T, method, path, badPath, body, badBody string) {
  1072. b := Query
  1073. assert.Equal(t, "query", b.Name())
  1074. obj := FooBarStruct{}
  1075. req := requestWithBody(method, path, body)
  1076. if method == "POST" {
  1077. req.Header.Add("Content-Type", MIMEPOSTForm)
  1078. }
  1079. err := b.Bind(req, &obj)
  1080. assert.NoError(t, err)
  1081. assert.Equal(t, "bar", obj.Foo)
  1082. assert.Equal(t, "foo", obj.Bar)
  1083. }
  1084. func testQueryBindingFail(t *testing.T, method, path, badPath, body, badBody string) {
  1085. b := Query
  1086. assert.Equal(t, "query", b.Name())
  1087. obj := FooStructForMapType{}
  1088. req := requestWithBody(method, path, body)
  1089. if method == "POST" {
  1090. req.Header.Add("Content-Type", MIMEPOSTForm)
  1091. }
  1092. err := b.Bind(req, &obj)
  1093. assert.Error(t, err)
  1094. }
  1095. func testQueryBindingBoolFail(t *testing.T, method, path, badPath, body, badBody string) {
  1096. b := Query
  1097. assert.Equal(t, "query", b.Name())
  1098. obj := FooStructForBoolType{}
  1099. req := requestWithBody(method, path, body)
  1100. if method == "POST" {
  1101. req.Header.Add("Content-Type", MIMEPOSTForm)
  1102. }
  1103. err := b.Bind(req, &obj)
  1104. assert.Error(t, err)
  1105. }
  1106. func testBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  1107. assert.Equal(t, name, b.Name())
  1108. obj := FooStruct{}
  1109. req := requestWithBody("POST", path, body)
  1110. err := b.Bind(req, &obj)
  1111. assert.NoError(t, err)
  1112. assert.Equal(t, "bar", obj.Foo)
  1113. obj = FooStruct{}
  1114. req = requestWithBody("POST", badPath, badBody)
  1115. err = JSON.Bind(req, &obj)
  1116. assert.Error(t, err)
  1117. }
  1118. func testBodyBindingUseNumber(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  1119. assert.Equal(t, name, b.Name())
  1120. obj := FooStructUseNumber{}
  1121. req := requestWithBody("POST", path, body)
  1122. EnableDecoderUseNumber = true
  1123. err := b.Bind(req, &obj)
  1124. assert.NoError(t, err)
  1125. // we hope it is int64(123)
  1126. v, e := obj.Foo.(json.Number).Int64()
  1127. assert.NoError(t, e)
  1128. assert.Equal(t, int64(123), v)
  1129. obj = FooStructUseNumber{}
  1130. req = requestWithBody("POST", badPath, badBody)
  1131. err = JSON.Bind(req, &obj)
  1132. assert.Error(t, err)
  1133. }
  1134. func testBodyBindingUseNumber2(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  1135. assert.Equal(t, name, b.Name())
  1136. obj := FooStructUseNumber{}
  1137. req := requestWithBody("POST", path, body)
  1138. EnableDecoderUseNumber = false
  1139. err := b.Bind(req, &obj)
  1140. assert.NoError(t, err)
  1141. // it will return float64(123) if not use EnableDecoderUseNumber
  1142. // maybe it is not hoped
  1143. assert.Equal(t, float64(123), obj.Foo)
  1144. obj = FooStructUseNumber{}
  1145. req = requestWithBody("POST", badPath, badBody)
  1146. err = JSON.Bind(req, &obj)
  1147. assert.Error(t, err)
  1148. }
  1149. func testBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  1150. assert.Equal(t, name, b.Name())
  1151. obj := FooStruct{}
  1152. req := requestWithBody("POST", path, body)
  1153. err := b.Bind(req, &obj)
  1154. assert.Error(t, err)
  1155. assert.Equal(t, "", obj.Foo)
  1156. obj = FooStruct{}
  1157. req = requestWithBody("POST", badPath, badBody)
  1158. err = JSON.Bind(req, &obj)
  1159. assert.Error(t, err)
  1160. }
  1161. func testProtoBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  1162. assert.Equal(t, name, b.Name())
  1163. obj := protoexample.Test{}
  1164. req := requestWithBody("POST", path, body)
  1165. req.Header.Add("Content-Type", MIMEPROTOBUF)
  1166. err := b.Bind(req, &obj)
  1167. assert.NoError(t, err)
  1168. assert.Equal(t, "yes", *obj.Label)
  1169. obj = protoexample.Test{}
  1170. req = requestWithBody("POST", badPath, badBody)
  1171. req.Header.Add("Content-Type", MIMEPROTOBUF)
  1172. err = ProtoBuf.Bind(req, &obj)
  1173. assert.Error(t, err)
  1174. }
  1175. type hook struct{}
  1176. func (h hook) Read([]byte) (int, error) {
  1177. return 0, errors.New("error")
  1178. }
  1179. func testProtoBodyBindingFail(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  1180. assert.Equal(t, name, b.Name())
  1181. obj := protoexample.Test{}
  1182. req := requestWithBody("POST", path, body)
  1183. req.Body = ioutil.NopCloser(&hook{})
  1184. req.Header.Add("Content-Type", MIMEPROTOBUF)
  1185. err := b.Bind(req, &obj)
  1186. assert.Error(t, err)
  1187. obj = protoexample.Test{}
  1188. req = requestWithBody("POST", badPath, badBody)
  1189. req.Header.Add("Content-Type", MIMEPROTOBUF)
  1190. err = ProtoBuf.Bind(req, &obj)
  1191. assert.Error(t, err)
  1192. }
  1193. func testMsgPackBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
  1194. assert.Equal(t, name, b.Name())
  1195. obj := FooStruct{}
  1196. req := requestWithBody("POST", path, body)
  1197. req.Header.Add("Content-Type", MIMEMSGPACK)
  1198. err := b.Bind(req, &obj)
  1199. assert.NoError(t, err)
  1200. assert.Equal(t, "bar", obj.Foo)
  1201. obj = FooStruct{}
  1202. req = requestWithBody("POST", badPath, badBody)
  1203. req.Header.Add("Content-Type", MIMEMSGPACK)
  1204. err = MsgPack.Bind(req, &obj)
  1205. assert.Error(t, err)
  1206. }
  1207. func requestWithBody(method, path, body string) (req *http.Request) {
  1208. req, _ = http.NewRequest(method, path, bytes.NewBufferString(body))
  1209. return
  1210. }
  1211. func TestCanSet(t *testing.T) {
  1212. type CanSetStruct struct {
  1213. lowerStart string `form:"lower"`
  1214. }
  1215. var c CanSetStruct
  1216. assert.Nil(t, mapForm(&c, nil))
  1217. }
  1218. func formPostRequest(path, body string) *http.Request {
  1219. req := requestWithBody("POST", path, body)
  1220. req.Header.Add("Content-Type", MIMEPOSTForm)
  1221. return req
  1222. }
  1223. func TestBindingSliceDefault(t *testing.T) {
  1224. var s struct {
  1225. Friends []string `form:"friends,default=mike"`
  1226. }
  1227. req := formPostRequest("", "")
  1228. err := Form.Bind(req, &s)
  1229. assert.NoError(t, err)
  1230. assert.Len(t, s.Friends, 1)
  1231. assert.Equal(t, "mike", s.Friends[0])
  1232. }
  1233. func TestBindingStructField(t *testing.T) {
  1234. var s struct {
  1235. Opts struct {
  1236. Port int
  1237. } `form:"opts"`
  1238. }
  1239. req := formPostRequest("", `opts={"Port": 8000}`)
  1240. err := Form.Bind(req, &s)
  1241. assert.NoError(t, err)
  1242. assert.Equal(t, 8000, s.Opts.Port)
  1243. }
  1244. func TestBindingUnknownTypeChan(t *testing.T) {
  1245. var s struct {
  1246. Stop chan bool `form:"stop"`
  1247. }
  1248. req := formPostRequest("", "stop=true")
  1249. err := Form.Bind(req, &s)
  1250. assert.Error(t, err)
  1251. assert.Equal(t, errUnknownType, err)
  1252. }
  1253. func TestBindingTimeDuration(t *testing.T) {
  1254. var s struct {
  1255. Timeout time.Duration `form:"timeout"`
  1256. }
  1257. // ok
  1258. req := formPostRequest("", "timeout=5s")
  1259. err := Form.Bind(req, &s)
  1260. assert.NoError(t, err)
  1261. assert.Equal(t, 5*time.Second, s.Timeout)
  1262. // error
  1263. req = formPostRequest("", "timeout=wrong")
  1264. err = Form.Bind(req, &s)
  1265. assert.Error(t, err)
  1266. }
  1267. func TestBindingArray(t *testing.T) {
  1268. var s struct {
  1269. Nums [2]int `form:"nums,default=4"`
  1270. }
  1271. // default
  1272. req := formPostRequest("", "")
  1273. err := Form.Bind(req, &s)
  1274. assert.Error(t, err)
  1275. assert.Equal(t, [2]int{0, 0}, s.Nums)
  1276. // ok
  1277. req = formPostRequest("", "nums=3&nums=8")
  1278. err = Form.Bind(req, &s)
  1279. assert.NoError(t, err)
  1280. assert.Equal(t, [2]int{3, 8}, s.Nums)
  1281. // not enough vals
  1282. req = formPostRequest("", "nums=3")
  1283. err = Form.Bind(req, &s)
  1284. assert.Error(t, err)
  1285. // error
  1286. req = formPostRequest("", "nums=3&nums=wrong")
  1287. err = Form.Bind(req, &s)
  1288. assert.Error(t, err)
  1289. }