context_test.go 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  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 gin
  5. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "html/template"
  10. "io"
  11. "mime/multipart"
  12. "net/http"
  13. "net/http/httptest"
  14. "reflect"
  15. "strings"
  16. "testing"
  17. "time"
  18. "github.com/gin-contrib/sse"
  19. "github.com/gin-gonic/gin/binding"
  20. "github.com/golang/protobuf/proto"
  21. "github.com/stretchr/testify/assert"
  22. "golang.org/x/net/context"
  23. testdata "github.com/gin-gonic/gin/testdata/protoexample"
  24. )
  25. var _ context.Context = &Context{}
  26. // Unit tests TODO
  27. // func (c *Context) File(filepath string) {
  28. // func (c *Context) Negotiate(code int, config Negotiate) {
  29. // BAD case: func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
  30. // test that information is not leaked when reusing Contexts (using the Pool)
  31. func createMultipartRequest() *http.Request {
  32. boundary := "--testboundary"
  33. body := new(bytes.Buffer)
  34. mw := multipart.NewWriter(body)
  35. defer mw.Close()
  36. must(mw.SetBoundary(boundary))
  37. must(mw.WriteField("foo", "bar"))
  38. must(mw.WriteField("bar", "10"))
  39. must(mw.WriteField("bar", "foo2"))
  40. must(mw.WriteField("array", "first"))
  41. must(mw.WriteField("array", "second"))
  42. must(mw.WriteField("id", ""))
  43. must(mw.WriteField("time_local", "31/12/2016 14:55"))
  44. must(mw.WriteField("time_utc", "31/12/2016 14:55"))
  45. must(mw.WriteField("time_location", "31/12/2016 14:55"))
  46. must(mw.WriteField("names[a]", "thinkerou"))
  47. must(mw.WriteField("names[b]", "tianou"))
  48. req, err := http.NewRequest("POST", "/", body)
  49. must(err)
  50. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  51. return req
  52. }
  53. func must(err error) {
  54. if err != nil {
  55. panic(err.Error())
  56. }
  57. }
  58. func TestContextFormFile(t *testing.T) {
  59. buf := new(bytes.Buffer)
  60. mw := multipart.NewWriter(buf)
  61. w, err := mw.CreateFormFile("file", "test")
  62. if assert.NoError(t, err) {
  63. w.Write([]byte("test"))
  64. }
  65. mw.Close()
  66. c, _ := CreateTestContext(httptest.NewRecorder())
  67. c.Request, _ = http.NewRequest("POST", "/", buf)
  68. c.Request.Header.Set("Content-Type", mw.FormDataContentType())
  69. f, err := c.FormFile("file")
  70. if assert.NoError(t, err) {
  71. assert.Equal(t, "test", f.Filename)
  72. }
  73. assert.NoError(t, c.SaveUploadedFile(f, "test"))
  74. }
  75. func TestContextMultipartForm(t *testing.T) {
  76. buf := new(bytes.Buffer)
  77. mw := multipart.NewWriter(buf)
  78. mw.WriteField("foo", "bar")
  79. w, err := mw.CreateFormFile("file", "test")
  80. if assert.NoError(t, err) {
  81. w.Write([]byte("test"))
  82. }
  83. mw.Close()
  84. c, _ := CreateTestContext(httptest.NewRecorder())
  85. c.Request, _ = http.NewRequest("POST", "/", buf)
  86. c.Request.Header.Set("Content-Type", mw.FormDataContentType())
  87. f, err := c.MultipartForm()
  88. if assert.NoError(t, err) {
  89. assert.NotNil(t, f)
  90. }
  91. assert.NoError(t, c.SaveUploadedFile(f.File["file"][0], "test"))
  92. }
  93. func TestSaveUploadedOpenFailed(t *testing.T) {
  94. buf := new(bytes.Buffer)
  95. mw := multipart.NewWriter(buf)
  96. mw.Close()
  97. c, _ := CreateTestContext(httptest.NewRecorder())
  98. c.Request, _ = http.NewRequest("POST", "/", buf)
  99. c.Request.Header.Set("Content-Type", mw.FormDataContentType())
  100. f := &multipart.FileHeader{
  101. Filename: "file",
  102. }
  103. assert.Error(t, c.SaveUploadedFile(f, "test"))
  104. }
  105. func TestSaveUploadedCreateFailed(t *testing.T) {
  106. buf := new(bytes.Buffer)
  107. mw := multipart.NewWriter(buf)
  108. w, err := mw.CreateFormFile("file", "test")
  109. if assert.NoError(t, err) {
  110. w.Write([]byte("test"))
  111. }
  112. mw.Close()
  113. c, _ := CreateTestContext(httptest.NewRecorder())
  114. c.Request, _ = http.NewRequest("POST", "/", buf)
  115. c.Request.Header.Set("Content-Type", mw.FormDataContentType())
  116. f, err := c.FormFile("file")
  117. if assert.NoError(t, err) {
  118. assert.Equal(t, "test", f.Filename)
  119. }
  120. assert.Error(t, c.SaveUploadedFile(f, "/"))
  121. }
  122. func TestContextReset(t *testing.T) {
  123. router := New()
  124. c := router.allocateContext()
  125. assert.Equal(t, c.engine, router)
  126. c.index = 2
  127. c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()}
  128. c.Params = Params{Param{}}
  129. c.Error(errors.New("test"))
  130. c.Set("foo", "bar")
  131. c.reset()
  132. assert.False(t, c.IsAborted())
  133. assert.Nil(t, c.Keys)
  134. assert.Nil(t, c.Accepted)
  135. assert.Len(t, c.Errors, 0)
  136. assert.Empty(t, c.Errors.Errors())
  137. assert.Empty(t, c.Errors.ByType(ErrorTypeAny))
  138. assert.Len(t, c.Params, 0)
  139. assert.EqualValues(t, c.index, -1)
  140. assert.Equal(t, c.Writer.(*responseWriter), &c.writermem)
  141. }
  142. func TestContextHandlers(t *testing.T) {
  143. c, _ := CreateTestContext(httptest.NewRecorder())
  144. assert.Nil(t, c.handlers)
  145. assert.Nil(t, c.handlers.Last())
  146. c.handlers = HandlersChain{}
  147. assert.NotNil(t, c.handlers)
  148. assert.Nil(t, c.handlers.Last())
  149. f := func(c *Context) {}
  150. g := func(c *Context) {}
  151. c.handlers = HandlersChain{f}
  152. compareFunc(t, f, c.handlers.Last())
  153. c.handlers = HandlersChain{f, g}
  154. compareFunc(t, g, c.handlers.Last())
  155. }
  156. // TestContextSetGet tests that a parameter is set correctly on the
  157. // current context and can be retrieved using Get.
  158. func TestContextSetGet(t *testing.T) {
  159. c, _ := CreateTestContext(httptest.NewRecorder())
  160. c.Set("foo", "bar")
  161. value, err := c.Get("foo")
  162. assert.Equal(t, "bar", value)
  163. assert.True(t, err)
  164. value, err = c.Get("foo2")
  165. assert.Nil(t, value)
  166. assert.False(t, err)
  167. assert.Equal(t, "bar", c.MustGet("foo"))
  168. assert.Panics(t, func() { c.MustGet("no_exist") })
  169. }
  170. func TestContextSetGetValues(t *testing.T) {
  171. c, _ := CreateTestContext(httptest.NewRecorder())
  172. c.Set("string", "this is a string")
  173. c.Set("int32", int32(-42))
  174. c.Set("int64", int64(42424242424242))
  175. c.Set("uint64", uint64(42))
  176. c.Set("float32", float32(4.2))
  177. c.Set("float64", 4.2)
  178. var a interface{} = 1
  179. c.Set("intInterface", a)
  180. assert.Exactly(t, c.MustGet("string").(string), "this is a string")
  181. assert.Exactly(t, c.MustGet("int32").(int32), int32(-42))
  182. assert.Exactly(t, c.MustGet("int64").(int64), int64(42424242424242))
  183. assert.Exactly(t, c.MustGet("uint64").(uint64), uint64(42))
  184. assert.Exactly(t, c.MustGet("float32").(float32), float32(4.2))
  185. assert.Exactly(t, c.MustGet("float64").(float64), 4.2)
  186. assert.Exactly(t, c.MustGet("intInterface").(int), 1)
  187. }
  188. func TestContextGetString(t *testing.T) {
  189. c, _ := CreateTestContext(httptest.NewRecorder())
  190. c.Set("string", "this is a string")
  191. assert.Equal(t, "this is a string", c.GetString("string"))
  192. }
  193. func TestContextSetGetBool(t *testing.T) {
  194. c, _ := CreateTestContext(httptest.NewRecorder())
  195. c.Set("bool", true)
  196. assert.True(t, c.GetBool("bool"))
  197. }
  198. func TestContextGetInt(t *testing.T) {
  199. c, _ := CreateTestContext(httptest.NewRecorder())
  200. c.Set("int", 1)
  201. assert.Equal(t, 1, c.GetInt("int"))
  202. }
  203. func TestContextGetInt64(t *testing.T) {
  204. c, _ := CreateTestContext(httptest.NewRecorder())
  205. c.Set("int64", int64(42424242424242))
  206. assert.Equal(t, int64(42424242424242), c.GetInt64("int64"))
  207. }
  208. func TestContextGetFloat64(t *testing.T) {
  209. c, _ := CreateTestContext(httptest.NewRecorder())
  210. c.Set("float64", 4.2)
  211. assert.Equal(t, 4.2, c.GetFloat64("float64"))
  212. }
  213. func TestContextGetTime(t *testing.T) {
  214. c, _ := CreateTestContext(httptest.NewRecorder())
  215. t1, _ := time.Parse("1/2/2006 15:04:05", "01/01/2017 12:00:00")
  216. c.Set("time", t1)
  217. assert.Equal(t, t1, c.GetTime("time"))
  218. }
  219. func TestContextGetDuration(t *testing.T) {
  220. c, _ := CreateTestContext(httptest.NewRecorder())
  221. c.Set("duration", time.Second)
  222. assert.Equal(t, time.Second, c.GetDuration("duration"))
  223. }
  224. func TestContextGetStringSlice(t *testing.T) {
  225. c, _ := CreateTestContext(httptest.NewRecorder())
  226. c.Set("slice", []string{"foo"})
  227. assert.Equal(t, []string{"foo"}, c.GetStringSlice("slice"))
  228. }
  229. func TestContextGetStringMap(t *testing.T) {
  230. c, _ := CreateTestContext(httptest.NewRecorder())
  231. var m = make(map[string]interface{})
  232. m["foo"] = 1
  233. c.Set("map", m)
  234. assert.Equal(t, m, c.GetStringMap("map"))
  235. assert.Equal(t, 1, c.GetStringMap("map")["foo"])
  236. }
  237. func TestContextGetStringMapString(t *testing.T) {
  238. c, _ := CreateTestContext(httptest.NewRecorder())
  239. var m = make(map[string]string)
  240. m["foo"] = "bar"
  241. c.Set("map", m)
  242. assert.Equal(t, m, c.GetStringMapString("map"))
  243. assert.Equal(t, "bar", c.GetStringMapString("map")["foo"])
  244. }
  245. func TestContextGetStringMapStringSlice(t *testing.T) {
  246. c, _ := CreateTestContext(httptest.NewRecorder())
  247. var m = make(map[string][]string)
  248. m["foo"] = []string{"foo"}
  249. c.Set("map", m)
  250. assert.Equal(t, m, c.GetStringMapStringSlice("map"))
  251. assert.Equal(t, []string{"foo"}, c.GetStringMapStringSlice("map")["foo"])
  252. }
  253. func TestContextCopy(t *testing.T) {
  254. c, _ := CreateTestContext(httptest.NewRecorder())
  255. c.index = 2
  256. c.Request, _ = http.NewRequest("POST", "/hola", nil)
  257. c.handlers = HandlersChain{func(c *Context) {}}
  258. c.Params = Params{Param{Key: "foo", Value: "bar"}}
  259. c.Set("foo", "bar")
  260. cp := c.Copy()
  261. assert.Nil(t, cp.handlers)
  262. assert.Nil(t, cp.writermem.ResponseWriter)
  263. assert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))
  264. assert.Equal(t, cp.Request, c.Request)
  265. assert.Equal(t, cp.index, abortIndex)
  266. assert.Equal(t, cp.Keys, c.Keys)
  267. assert.Equal(t, cp.engine, c.engine)
  268. assert.Equal(t, cp.Params, c.Params)
  269. }
  270. func TestContextHandlerName(t *testing.T) {
  271. c, _ := CreateTestContext(httptest.NewRecorder())
  272. c.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}
  273. assert.Regexp(t, "^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$", c.HandlerName())
  274. }
  275. func handlerNameTest(c *Context) {
  276. }
  277. var handlerTest HandlerFunc = func(c *Context) {
  278. }
  279. func TestContextHandler(t *testing.T) {
  280. c, _ := CreateTestContext(httptest.NewRecorder())
  281. c.handlers = HandlersChain{func(c *Context) {}, handlerTest}
  282. assert.Equal(t, reflect.ValueOf(handlerTest).Pointer(), reflect.ValueOf(c.Handler()).Pointer())
  283. }
  284. func TestContextQuery(t *testing.T) {
  285. c, _ := CreateTestContext(httptest.NewRecorder())
  286. c.Request, _ = http.NewRequest("GET", "http://example.com/?foo=bar&page=10&id=", nil)
  287. value, ok := c.GetQuery("foo")
  288. assert.True(t, ok)
  289. assert.Equal(t, "bar", value)
  290. assert.Equal(t, "bar", c.DefaultQuery("foo", "none"))
  291. assert.Equal(t, "bar", c.Query("foo"))
  292. value, ok = c.GetQuery("page")
  293. assert.True(t, ok)
  294. assert.Equal(t, "10", value)
  295. assert.Equal(t, "10", c.DefaultQuery("page", "0"))
  296. assert.Equal(t, "10", c.Query("page"))
  297. value, ok = c.GetQuery("id")
  298. assert.True(t, ok)
  299. assert.Empty(t, value)
  300. assert.Empty(t, c.DefaultQuery("id", "nada"))
  301. assert.Empty(t, c.Query("id"))
  302. value, ok = c.GetQuery("NoKey")
  303. assert.False(t, ok)
  304. assert.Empty(t, value)
  305. assert.Equal(t, "nada", c.DefaultQuery("NoKey", "nada"))
  306. assert.Empty(t, c.Query("NoKey"))
  307. // postform should not mess
  308. value, ok = c.GetPostForm("page")
  309. assert.False(t, ok)
  310. assert.Empty(t, value)
  311. assert.Empty(t, c.PostForm("foo"))
  312. }
  313. func TestContextQueryAndPostForm(t *testing.T) {
  314. c, _ := CreateTestContext(httptest.NewRecorder())
  315. body := bytes.NewBufferString("foo=bar&page=11&both=&foo=second")
  316. c.Request, _ = http.NewRequest("POST",
  317. "/?both=GET&id=main&id=omit&array[]=first&array[]=second&ids[a]=hi&ids[b]=3.14", body)
  318. c.Request.Header.Add("Content-Type", MIMEPOSTForm)
  319. assert.Equal(t, "bar", c.DefaultPostForm("foo", "none"))
  320. assert.Equal(t, "bar", c.PostForm("foo"))
  321. assert.Empty(t, c.Query("foo"))
  322. value, ok := c.GetPostForm("page")
  323. assert.True(t, ok)
  324. assert.Equal(t, "11", value)
  325. assert.Equal(t, "11", c.DefaultPostForm("page", "0"))
  326. assert.Equal(t, "11", c.PostForm("page"))
  327. assert.Empty(t, c.Query("page"))
  328. value, ok = c.GetPostForm("both")
  329. assert.True(t, ok)
  330. assert.Empty(t, value)
  331. assert.Empty(t, c.PostForm("both"))
  332. assert.Empty(t, c.DefaultPostForm("both", "nothing"))
  333. assert.Equal(t, "GET", c.Query("both"), "GET")
  334. value, ok = c.GetQuery("id")
  335. assert.True(t, ok)
  336. assert.Equal(t, "main", value)
  337. assert.Equal(t, "000", c.DefaultPostForm("id", "000"))
  338. assert.Equal(t, "main", c.Query("id"))
  339. assert.Empty(t, c.PostForm("id"))
  340. value, ok = c.GetQuery("NoKey")
  341. assert.False(t, ok)
  342. assert.Empty(t, value)
  343. value, ok = c.GetPostForm("NoKey")
  344. assert.False(t, ok)
  345. assert.Empty(t, value)
  346. assert.Equal(t, "nada", c.DefaultPostForm("NoKey", "nada"))
  347. assert.Equal(t, "nothing", c.DefaultQuery("NoKey", "nothing"))
  348. assert.Empty(t, c.PostForm("NoKey"))
  349. assert.Empty(t, c.Query("NoKey"))
  350. var obj struct {
  351. Foo string `form:"foo"`
  352. ID string `form:"id"`
  353. Page int `form:"page"`
  354. Both string `form:"both"`
  355. Array []string `form:"array[]"`
  356. }
  357. assert.NoError(t, c.Bind(&obj))
  358. assert.Equal(t, "bar", obj.Foo, "bar")
  359. assert.Equal(t, "main", obj.ID, "main")
  360. assert.Equal(t, 11, obj.Page, 11)
  361. assert.Empty(t, obj.Both)
  362. assert.Equal(t, []string{"first", "second"}, obj.Array)
  363. values, ok := c.GetQueryArray("array[]")
  364. assert.True(t, ok)
  365. assert.Equal(t, "first", values[0])
  366. assert.Equal(t, "second", values[1])
  367. values = c.QueryArray("array[]")
  368. assert.Equal(t, "first", values[0])
  369. assert.Equal(t, "second", values[1])
  370. values = c.QueryArray("nokey")
  371. assert.Equal(t, 0, len(values))
  372. values = c.QueryArray("both")
  373. assert.Equal(t, 1, len(values))
  374. assert.Equal(t, "GET", values[0])
  375. dicts, ok := c.GetQueryMap("ids")
  376. assert.True(t, ok)
  377. assert.Equal(t, "hi", dicts["a"])
  378. assert.Equal(t, "3.14", dicts["b"])
  379. dicts, ok = c.GetQueryMap("nokey")
  380. assert.False(t, ok)
  381. assert.Equal(t, 0, len(dicts))
  382. dicts, ok = c.GetQueryMap("both")
  383. assert.False(t, ok)
  384. assert.Equal(t, 0, len(dicts))
  385. dicts, ok = c.GetQueryMap("array")
  386. assert.False(t, ok)
  387. assert.Equal(t, 0, len(dicts))
  388. dicts = c.QueryMap("ids")
  389. assert.Equal(t, "hi", dicts["a"])
  390. assert.Equal(t, "3.14", dicts["b"])
  391. dicts = c.QueryMap("nokey")
  392. assert.Equal(t, 0, len(dicts))
  393. }
  394. func TestContextPostFormMultipart(t *testing.T) {
  395. c, _ := CreateTestContext(httptest.NewRecorder())
  396. c.Request = createMultipartRequest()
  397. var obj struct {
  398. Foo string `form:"foo"`
  399. Bar string `form:"bar"`
  400. BarAsInt int `form:"bar"`
  401. Array []string `form:"array"`
  402. ID string `form:"id"`
  403. TimeLocal time.Time `form:"time_local" time_format:"02/01/2006 15:04"`
  404. TimeUTC time.Time `form:"time_utc" time_format:"02/01/2006 15:04" time_utc:"1"`
  405. TimeLocation time.Time `form:"time_location" time_format:"02/01/2006 15:04" time_location:"Asia/Tokyo"`
  406. BlankTime time.Time `form:"blank_time" time_format:"02/01/2006 15:04"`
  407. }
  408. assert.NoError(t, c.Bind(&obj))
  409. assert.Equal(t, "bar", obj.Foo)
  410. assert.Equal(t, "10", obj.Bar)
  411. assert.Equal(t, 10, obj.BarAsInt)
  412. assert.Equal(t, []string{"first", "second"}, obj.Array)
  413. assert.Empty(t, obj.ID)
  414. assert.Equal(t, "31/12/2016 14:55", obj.TimeLocal.Format("02/01/2006 15:04"))
  415. assert.Equal(t, time.Local, obj.TimeLocal.Location())
  416. assert.Equal(t, "31/12/2016 14:55", obj.TimeUTC.Format("02/01/2006 15:04"))
  417. assert.Equal(t, time.UTC, obj.TimeUTC.Location())
  418. loc, _ := time.LoadLocation("Asia/Tokyo")
  419. assert.Equal(t, "31/12/2016 14:55", obj.TimeLocation.Format("02/01/2006 15:04"))
  420. assert.Equal(t, loc, obj.TimeLocation.Location())
  421. assert.True(t, obj.BlankTime.IsZero())
  422. value, ok := c.GetQuery("foo")
  423. assert.False(t, ok)
  424. assert.Empty(t, value)
  425. assert.Empty(t, c.Query("bar"))
  426. assert.Equal(t, "nothing", c.DefaultQuery("id", "nothing"))
  427. value, ok = c.GetPostForm("foo")
  428. assert.True(t, ok)
  429. assert.Equal(t, "bar", value)
  430. assert.Equal(t, "bar", c.PostForm("foo"))
  431. value, ok = c.GetPostForm("array")
  432. assert.True(t, ok)
  433. assert.Equal(t, "first", value)
  434. assert.Equal(t, "first", c.PostForm("array"))
  435. assert.Equal(t, "10", c.DefaultPostForm("bar", "nothing"))
  436. value, ok = c.GetPostForm("id")
  437. assert.True(t, ok)
  438. assert.Empty(t, value)
  439. assert.Empty(t, c.PostForm("id"))
  440. assert.Empty(t, c.DefaultPostForm("id", "nothing"))
  441. value, ok = c.GetPostForm("nokey")
  442. assert.False(t, ok)
  443. assert.Empty(t, value)
  444. assert.Equal(t, "nothing", c.DefaultPostForm("nokey", "nothing"))
  445. values, ok := c.GetPostFormArray("array")
  446. assert.True(t, ok)
  447. assert.Equal(t, "first", values[0])
  448. assert.Equal(t, "second", values[1])
  449. values = c.PostFormArray("array")
  450. assert.Equal(t, "first", values[0])
  451. assert.Equal(t, "second", values[1])
  452. values = c.PostFormArray("nokey")
  453. assert.Equal(t, 0, len(values))
  454. values = c.PostFormArray("foo")
  455. assert.Equal(t, 1, len(values))
  456. assert.Equal(t, "bar", values[0])
  457. dicts, ok := c.GetPostFormMap("names")
  458. assert.True(t, ok)
  459. assert.Equal(t, "thinkerou", dicts["a"])
  460. assert.Equal(t, "tianou", dicts["b"])
  461. dicts, ok = c.GetPostFormMap("nokey")
  462. assert.False(t, ok)
  463. assert.Equal(t, 0, len(dicts))
  464. dicts = c.PostFormMap("names")
  465. assert.Equal(t, "thinkerou", dicts["a"])
  466. assert.Equal(t, "tianou", dicts["b"])
  467. dicts = c.PostFormMap("nokey")
  468. assert.Equal(t, 0, len(dicts))
  469. }
  470. func TestContextSetCookie(t *testing.T) {
  471. c, _ := CreateTestContext(httptest.NewRecorder())
  472. c.SetCookie("user", "gin", 1, "/", "localhost", true, true)
  473. assert.Equal(t, "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure", c.Writer.Header().Get("Set-Cookie"))
  474. }
  475. func TestContextSetCookiePathEmpty(t *testing.T) {
  476. c, _ := CreateTestContext(httptest.NewRecorder())
  477. c.SetCookie("user", "gin", 1, "", "localhost", true, true)
  478. assert.Equal(t, "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure", c.Writer.Header().Get("Set-Cookie"))
  479. }
  480. func TestContextGetCookie(t *testing.T) {
  481. c, _ := CreateTestContext(httptest.NewRecorder())
  482. c.Request, _ = http.NewRequest("GET", "/get", nil)
  483. c.Request.Header.Set("Cookie", "user=gin")
  484. cookie, _ := c.Cookie("user")
  485. assert.Equal(t, "gin", cookie)
  486. _, err := c.Cookie("nokey")
  487. assert.Error(t, err)
  488. }
  489. func TestContextBodyAllowedForStatus(t *testing.T) {
  490. // todo(thinkerou): go1.6 not support StatusProcessing
  491. assert.False(t, false, bodyAllowedForStatus(102))
  492. assert.False(t, false, bodyAllowedForStatus(http.StatusNoContent))
  493. assert.False(t, false, bodyAllowedForStatus(http.StatusNotModified))
  494. assert.True(t, true, bodyAllowedForStatus(http.StatusInternalServerError))
  495. }
  496. type TestPanicRender struct {
  497. }
  498. func (*TestPanicRender) Render(http.ResponseWriter) error {
  499. return errors.New("TestPanicRender")
  500. }
  501. func (*TestPanicRender) WriteContentType(http.ResponseWriter) {}
  502. func TestContextRenderPanicIfErr(t *testing.T) {
  503. defer func() {
  504. r := recover()
  505. assert.Equal(t, "TestPanicRender", fmt.Sprint(r))
  506. }()
  507. w := httptest.NewRecorder()
  508. c, _ := CreateTestContext(w)
  509. c.Render(http.StatusOK, &TestPanicRender{})
  510. assert.Fail(t, "Panic not detected")
  511. }
  512. // Tests that the response is serialized as JSON
  513. // and Content-Type is set to application/json
  514. func TestContextRenderJSON(t *testing.T) {
  515. w := httptest.NewRecorder()
  516. c, _ := CreateTestContext(w)
  517. c.JSON(http.StatusCreated, H{"foo": "bar"})
  518. assert.Equal(t, http.StatusCreated, w.Code)
  519. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  520. assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  521. }
  522. // Tests that the response is serialized as JSONP
  523. // and Content-Type is set to application/javascript
  524. func TestContextRenderJSONP(t *testing.T) {
  525. w := httptest.NewRecorder()
  526. c, _ := CreateTestContext(w)
  527. c.Request, _ = http.NewRequest("GET", "http://example.com/?callback=x", nil)
  528. c.JSONP(http.StatusCreated, H{"foo": "bar"})
  529. assert.Equal(t, http.StatusCreated, w.Code)
  530. assert.Equal(t, "x({\"foo\":\"bar\"})", w.Body.String())
  531. assert.Equal(t, "application/javascript; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  532. }
  533. // Tests that the response is serialized as JSONP
  534. // and Content-Type is set to application/json
  535. func TestContextRenderJSONPWithoutCallback(t *testing.T) {
  536. w := httptest.NewRecorder()
  537. c, _ := CreateTestContext(w)
  538. c.Request, _ = http.NewRequest("GET", "http://example.com", nil)
  539. c.JSONP(http.StatusCreated, H{"foo": "bar"})
  540. assert.Equal(t, http.StatusCreated, w.Code)
  541. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  542. assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  543. }
  544. // Tests that no JSON is rendered if code is 204
  545. func TestContextRenderNoContentJSON(t *testing.T) {
  546. w := httptest.NewRecorder()
  547. c, _ := CreateTestContext(w)
  548. c.JSON(http.StatusNoContent, H{"foo": "bar"})
  549. assert.Equal(t, http.StatusNoContent, w.Code)
  550. assert.Empty(t, w.Body.String())
  551. assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  552. }
  553. // Tests that the response is serialized as JSON
  554. // we change the content-type before
  555. func TestContextRenderAPIJSON(t *testing.T) {
  556. w := httptest.NewRecorder()
  557. c, _ := CreateTestContext(w)
  558. c.Header("Content-Type", "application/vnd.api+json")
  559. c.JSON(http.StatusCreated, H{"foo": "bar"})
  560. assert.Equal(t, http.StatusCreated, w.Code)
  561. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  562. assert.Equal(t, "application/vnd.api+json", w.HeaderMap.Get("Content-Type"))
  563. }
  564. // Tests that no Custom JSON is rendered if code is 204
  565. func TestContextRenderNoContentAPIJSON(t *testing.T) {
  566. w := httptest.NewRecorder()
  567. c, _ := CreateTestContext(w)
  568. c.Header("Content-Type", "application/vnd.api+json")
  569. c.JSON(http.StatusNoContent, H{"foo": "bar"})
  570. assert.Equal(t, http.StatusNoContent, w.Code)
  571. assert.Empty(t, w.Body.String())
  572. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/vnd.api+json")
  573. }
  574. // Tests that the response is serialized as JSON
  575. // and Content-Type is set to application/json
  576. func TestContextRenderIndentedJSON(t *testing.T) {
  577. w := httptest.NewRecorder()
  578. c, _ := CreateTestContext(w)
  579. c.IndentedJSON(http.StatusCreated, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  580. assert.Equal(t, http.StatusCreated, w.Code)
  581. assert.Equal(t, "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}", w.Body.String())
  582. assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  583. }
  584. // Tests that no Custom JSON is rendered if code is 204
  585. func TestContextRenderNoContentIndentedJSON(t *testing.T) {
  586. w := httptest.NewRecorder()
  587. c, _ := CreateTestContext(w)
  588. c.IndentedJSON(http.StatusNoContent, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  589. assert.Equal(t, http.StatusNoContent, w.Code)
  590. assert.Empty(t, w.Body.String())
  591. assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  592. }
  593. // Tests that the response is serialized as Secure JSON
  594. // and Content-Type is set to application/json
  595. func TestContextRenderSecureJSON(t *testing.T) {
  596. w := httptest.NewRecorder()
  597. c, router := CreateTestContext(w)
  598. router.SecureJsonPrefix("&&&START&&&")
  599. c.SecureJSON(http.StatusCreated, []string{"foo", "bar"})
  600. assert.Equal(t, http.StatusCreated, w.Code)
  601. assert.Equal(t, "&&&START&&&[\"foo\",\"bar\"]", w.Body.String())
  602. assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  603. }
  604. // Tests that no Custom JSON is rendered if code is 204
  605. func TestContextRenderNoContentSecureJSON(t *testing.T) {
  606. w := httptest.NewRecorder()
  607. c, _ := CreateTestContext(w)
  608. c.SecureJSON(http.StatusNoContent, []string{"foo", "bar"})
  609. assert.Equal(t, http.StatusNoContent, w.Code)
  610. assert.Empty(t, w.Body.String())
  611. assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  612. }
  613. func TestContextRenderNoContentAsciiJSON(t *testing.T) {
  614. w := httptest.NewRecorder()
  615. c, _ := CreateTestContext(w)
  616. c.AsciiJSON(http.StatusNoContent, []string{"lang", "Go语言"})
  617. assert.Equal(t, http.StatusNoContent, w.Code)
  618. assert.Empty(t, w.Body.String())
  619. assert.Equal(t, "application/json", w.HeaderMap.Get("Content-Type"))
  620. }
  621. // Tests that the response executes the templates
  622. // and responds with Content-Type set to text/html
  623. func TestContextRenderHTML(t *testing.T) {
  624. w := httptest.NewRecorder()
  625. c, router := CreateTestContext(w)
  626. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  627. router.SetHTMLTemplate(templ)
  628. c.HTML(http.StatusCreated, "t", H{"name": "alexandernyquist"})
  629. assert.Equal(t, http.StatusCreated, w.Code)
  630. assert.Equal(t, "Hello alexandernyquist", w.Body.String())
  631. assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  632. }
  633. func TestContextRenderHTML2(t *testing.T) {
  634. w := httptest.NewRecorder()
  635. c, router := CreateTestContext(w)
  636. // print debug warning log when Engine.trees > 0
  637. router.addRoute("GET", "/", HandlersChain{func(_ *Context) {}})
  638. assert.Len(t, router.trees, 1)
  639. var b bytes.Buffer
  640. setup(&b)
  641. defer teardown()
  642. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  643. router.SetHTMLTemplate(templ)
  644. assert.Equal(t, "[GIN-debug] [WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called\nat initialization. ie. before any route is registered or the router is listening in a socket:\n\n\trouter := gin.Default()\n\trouter.SetHTMLTemplate(template) // << good place\n\n", b.String())
  645. c.HTML(http.StatusCreated, "t", H{"name": "alexandernyquist"})
  646. assert.Equal(t, http.StatusCreated, w.Code)
  647. assert.Equal(t, "Hello alexandernyquist", w.Body.String())
  648. assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  649. }
  650. // Tests that no HTML is rendered if code is 204
  651. func TestContextRenderNoContentHTML(t *testing.T) {
  652. w := httptest.NewRecorder()
  653. c, router := CreateTestContext(w)
  654. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  655. router.SetHTMLTemplate(templ)
  656. c.HTML(http.StatusNoContent, "t", H{"name": "alexandernyquist"})
  657. assert.Equal(t, http.StatusNoContent, w.Code)
  658. assert.Empty(t, w.Body.String())
  659. assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  660. }
  661. // TestContextXML tests that the response is serialized as XML
  662. // and Content-Type is set to application/xml
  663. func TestContextRenderXML(t *testing.T) {
  664. w := httptest.NewRecorder()
  665. c, _ := CreateTestContext(w)
  666. c.XML(http.StatusCreated, H{"foo": "bar"})
  667. assert.Equal(t, http.StatusCreated, w.Code)
  668. assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String())
  669. assert.Equal(t, "application/xml; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  670. }
  671. // Tests that no XML is rendered if code is 204
  672. func TestContextRenderNoContentXML(t *testing.T) {
  673. w := httptest.NewRecorder()
  674. c, _ := CreateTestContext(w)
  675. c.XML(http.StatusNoContent, H{"foo": "bar"})
  676. assert.Equal(t, http.StatusNoContent, w.Code)
  677. assert.Empty(t, w.Body.String())
  678. assert.Equal(t, "application/xml; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  679. }
  680. // TestContextString tests that the response is returned
  681. // with Content-Type set to text/plain
  682. func TestContextRenderString(t *testing.T) {
  683. w := httptest.NewRecorder()
  684. c, _ := CreateTestContext(w)
  685. c.String(http.StatusCreated, "test %s %d", "string", 2)
  686. assert.Equal(t, http.StatusCreated, w.Code)
  687. assert.Equal(t, "test string 2", w.Body.String())
  688. assert.Equal(t, "text/plain; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  689. }
  690. // Tests that no String is rendered if code is 204
  691. func TestContextRenderNoContentString(t *testing.T) {
  692. w := httptest.NewRecorder()
  693. c, _ := CreateTestContext(w)
  694. c.String(http.StatusNoContent, "test %s %d", "string", 2)
  695. assert.Equal(t, http.StatusNoContent, w.Code)
  696. assert.Empty(t, w.Body.String())
  697. assert.Equal(t, "text/plain; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  698. }
  699. // TestContextString tests that the response is returned
  700. // with Content-Type set to text/html
  701. func TestContextRenderHTMLString(t *testing.T) {
  702. w := httptest.NewRecorder()
  703. c, _ := CreateTestContext(w)
  704. c.Header("Content-Type", "text/html; charset=utf-8")
  705. c.String(http.StatusCreated, "<html>%s %d</html>", "string", 3)
  706. assert.Equal(t, http.StatusCreated, w.Code)
  707. assert.Equal(t, "<html>string 3</html>", w.Body.String())
  708. assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  709. }
  710. // Tests that no HTML String is rendered if code is 204
  711. func TestContextRenderNoContentHTMLString(t *testing.T) {
  712. w := httptest.NewRecorder()
  713. c, _ := CreateTestContext(w)
  714. c.Header("Content-Type", "text/html; charset=utf-8")
  715. c.String(http.StatusNoContent, "<html>%s %d</html>", "string", 3)
  716. assert.Equal(t, http.StatusNoContent, w.Code)
  717. assert.Empty(t, w.Body.String())
  718. assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  719. }
  720. // TestContextData tests that the response can be written from `bytesting`
  721. // with specified MIME type
  722. func TestContextRenderData(t *testing.T) {
  723. w := httptest.NewRecorder()
  724. c, _ := CreateTestContext(w)
  725. c.Data(http.StatusCreated, "text/csv", []byte(`foo,bar`))
  726. assert.Equal(t, http.StatusCreated, w.Code)
  727. assert.Equal(t, "foo,bar", w.Body.String())
  728. assert.Equal(t, "text/csv", w.HeaderMap.Get("Content-Type"))
  729. }
  730. // Tests that no Custom Data is rendered if code is 204
  731. func TestContextRenderNoContentData(t *testing.T) {
  732. w := httptest.NewRecorder()
  733. c, _ := CreateTestContext(w)
  734. c.Data(http.StatusNoContent, "text/csv", []byte(`foo,bar`))
  735. assert.Equal(t, http.StatusNoContent, w.Code)
  736. assert.Empty(t, w.Body.String())
  737. assert.Equal(t, "text/csv", w.HeaderMap.Get("Content-Type"))
  738. }
  739. func TestContextRenderSSE(t *testing.T) {
  740. w := httptest.NewRecorder()
  741. c, _ := CreateTestContext(w)
  742. c.SSEvent("float", 1.5)
  743. c.Render(-1, sse.Event{
  744. Id: "123",
  745. Data: "text",
  746. })
  747. c.SSEvent("chat", H{
  748. "foo": "bar",
  749. "bar": "foo",
  750. })
  751. assert.Equal(t, strings.Replace(w.Body.String(), " ", "", -1), strings.Replace("event:float\ndata:1.5\n\nid:123\ndata:text\n\nevent:chat\ndata:{\"bar\":\"foo\",\"foo\":\"bar\"}\n\n", " ", "", -1))
  752. }
  753. func TestContextRenderFile(t *testing.T) {
  754. w := httptest.NewRecorder()
  755. c, _ := CreateTestContext(w)
  756. c.Request, _ = http.NewRequest("GET", "/", nil)
  757. c.File("./gin.go")
  758. assert.Equal(t, http.StatusOK, w.Code)
  759. assert.Contains(t, w.Body.String(), "func New() *Engine {")
  760. assert.Equal(t, "text/plain; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  761. }
  762. // TestContextRenderYAML tests that the response is serialized as YAML
  763. // and Content-Type is set to application/x-yaml
  764. func TestContextRenderYAML(t *testing.T) {
  765. w := httptest.NewRecorder()
  766. c, _ := CreateTestContext(w)
  767. c.YAML(http.StatusCreated, H{"foo": "bar"})
  768. assert.Equal(t, http.StatusCreated, w.Code)
  769. assert.Equal(t, "foo: bar\n", w.Body.String())
  770. assert.Equal(t, "application/x-yaml; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  771. }
  772. // TestContextRenderProtoBuf tests that the response is serialized as ProtoBuf
  773. // and Content-Type is set to application/x-protobuf
  774. // and we just use the example protobuf to check if the response is correct
  775. func TestContextRenderProtoBuf(t *testing.T) {
  776. w := httptest.NewRecorder()
  777. c, _ := CreateTestContext(w)
  778. reps := []int64{int64(1), int64(2)}
  779. label := "test"
  780. data := &testdata.Test{
  781. Label: &label,
  782. Reps: reps,
  783. }
  784. c.ProtoBuf(http.StatusCreated, data)
  785. protoData, err := proto.Marshal(data)
  786. assert.NoError(t, err)
  787. assert.Equal(t, http.StatusCreated, w.Code)
  788. assert.Equal(t, string(protoData[:]), w.Body.String())
  789. assert.Equal(t, "application/x-protobuf", w.HeaderMap.Get("Content-Type"))
  790. }
  791. func TestContextHeaders(t *testing.T) {
  792. c, _ := CreateTestContext(httptest.NewRecorder())
  793. c.Header("Content-Type", "text/plain")
  794. c.Header("X-Custom", "value")
  795. assert.Equal(t, "text/plain", c.Writer.Header().Get("Content-Type"))
  796. assert.Equal(t, "value", c.Writer.Header().Get("X-Custom"))
  797. c.Header("Content-Type", "text/html")
  798. c.Header("X-Custom", "")
  799. assert.Equal(t, "text/html", c.Writer.Header().Get("Content-Type"))
  800. _, exist := c.Writer.Header()["X-Custom"]
  801. assert.False(t, exist)
  802. }
  803. // TODO
  804. func TestContextRenderRedirectWithRelativePath(t *testing.T) {
  805. w := httptest.NewRecorder()
  806. c, _ := CreateTestContext(w)
  807. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  808. assert.Panics(t, func() { c.Redirect(299, "/new_path") })
  809. assert.Panics(t, func() { c.Redirect(309, "/new_path") })
  810. c.Redirect(http.StatusMovedPermanently, "/path")
  811. c.Writer.WriteHeaderNow()
  812. assert.Equal(t, http.StatusMovedPermanently, w.Code)
  813. assert.Equal(t, "/path", w.Header().Get("Location"))
  814. }
  815. func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
  816. w := httptest.NewRecorder()
  817. c, _ := CreateTestContext(w)
  818. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  819. c.Redirect(http.StatusFound, "http://google.com")
  820. c.Writer.WriteHeaderNow()
  821. assert.Equal(t, http.StatusFound, w.Code)
  822. assert.Equal(t, "http://google.com", w.Header().Get("Location"))
  823. }
  824. func TestContextRenderRedirectWith201(t *testing.T) {
  825. w := httptest.NewRecorder()
  826. c, _ := CreateTestContext(w)
  827. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  828. c.Redirect(http.StatusCreated, "/resource")
  829. c.Writer.WriteHeaderNow()
  830. assert.Equal(t, http.StatusCreated, w.Code)
  831. assert.Equal(t, "/resource", w.Header().Get("Location"))
  832. }
  833. func TestContextRenderRedirectAll(t *testing.T) {
  834. c, _ := CreateTestContext(httptest.NewRecorder())
  835. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  836. assert.Panics(t, func() { c.Redirect(http.StatusOK, "/resource") })
  837. assert.Panics(t, func() { c.Redirect(http.StatusAccepted, "/resource") })
  838. assert.Panics(t, func() { c.Redirect(299, "/resource") })
  839. assert.Panics(t, func() { c.Redirect(309, "/resource") })
  840. assert.NotPanics(t, func() { c.Redirect(http.StatusMultipleChoices, "/resource") })
  841. // todo(thinkerou): go1.6 not support StatusPermanentRedirect(308)
  842. // when we upgrade go version we can use http.StatusPermanentRedirect
  843. assert.NotPanics(t, func() { c.Redirect(308, "/resource") })
  844. }
  845. func TestContextNegotiationWithJSON(t *testing.T) {
  846. w := httptest.NewRecorder()
  847. c, _ := CreateTestContext(w)
  848. c.Request, _ = http.NewRequest("POST", "", nil)
  849. c.Negotiate(http.StatusOK, Negotiate{
  850. Offered: []string{MIMEJSON, MIMEXML},
  851. Data: H{"foo": "bar"},
  852. })
  853. assert.Equal(t, http.StatusOK, w.Code)
  854. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  855. assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  856. }
  857. func TestContextNegotiationWithXML(t *testing.T) {
  858. w := httptest.NewRecorder()
  859. c, _ := CreateTestContext(w)
  860. c.Request, _ = http.NewRequest("POST", "", nil)
  861. c.Negotiate(http.StatusOK, Negotiate{
  862. Offered: []string{MIMEXML, MIMEJSON},
  863. Data: H{"foo": "bar"},
  864. })
  865. assert.Equal(t, http.StatusOK, w.Code)
  866. assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String())
  867. assert.Equal(t, "application/xml; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  868. }
  869. func TestContextNegotiationWithHTML(t *testing.T) {
  870. w := httptest.NewRecorder()
  871. c, router := CreateTestContext(w)
  872. c.Request, _ = http.NewRequest("POST", "", nil)
  873. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  874. router.SetHTMLTemplate(templ)
  875. c.Negotiate(http.StatusOK, Negotiate{
  876. Offered: []string{MIMEHTML},
  877. Data: H{"name": "gin"},
  878. HTMLName: "t",
  879. })
  880. assert.Equal(t, http.StatusOK, w.Code)
  881. assert.Equal(t, "Hello gin", w.Body.String())
  882. assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  883. }
  884. func TestContextNegotiationNotSupport(t *testing.T) {
  885. w := httptest.NewRecorder()
  886. c, _ := CreateTestContext(w)
  887. c.Request, _ = http.NewRequest("POST", "", nil)
  888. c.Negotiate(http.StatusOK, Negotiate{
  889. Offered: []string{MIMEPOSTForm},
  890. })
  891. assert.Equal(t, http.StatusNotAcceptable, w.Code)
  892. assert.Equal(t, c.index, abortIndex)
  893. assert.True(t, c.IsAborted())
  894. }
  895. func TestContextNegotiationFormat(t *testing.T) {
  896. c, _ := CreateTestContext(httptest.NewRecorder())
  897. c.Request, _ = http.NewRequest("POST", "", nil)
  898. assert.Panics(t, func() { c.NegotiateFormat() })
  899. assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON, MIMEXML))
  900. assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEHTML, MIMEJSON))
  901. }
  902. func TestContextNegotiationFormatWithAccept(t *testing.T) {
  903. c, _ := CreateTestContext(httptest.NewRecorder())
  904. c.Request, _ = http.NewRequest("POST", "/", nil)
  905. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  906. assert.Equal(t, MIMEXML, c.NegotiateFormat(MIMEJSON, MIMEXML))
  907. assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEXML, MIMEHTML))
  908. assert.Empty(t, c.NegotiateFormat(MIMEJSON))
  909. }
  910. func TestContextNegotiationFormatCustum(t *testing.T) {
  911. c, _ := CreateTestContext(httptest.NewRecorder())
  912. c.Request, _ = http.NewRequest("POST", "/", nil)
  913. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  914. c.Accepted = nil
  915. c.SetAccepted(MIMEJSON, MIMEXML)
  916. assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON, MIMEXML))
  917. assert.Equal(t, MIMEXML, c.NegotiateFormat(MIMEXML, MIMEHTML))
  918. assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON))
  919. }
  920. func TestContextIsAborted(t *testing.T) {
  921. c, _ := CreateTestContext(httptest.NewRecorder())
  922. assert.False(t, c.IsAborted())
  923. c.Abort()
  924. assert.True(t, c.IsAborted())
  925. c.Next()
  926. assert.True(t, c.IsAborted())
  927. c.index++
  928. assert.True(t, c.IsAborted())
  929. }
  930. // TestContextData tests that the response can be written from `bytesting`
  931. // with specified MIME type
  932. func TestContextAbortWithStatus(t *testing.T) {
  933. w := httptest.NewRecorder()
  934. c, _ := CreateTestContext(w)
  935. c.index = 4
  936. c.AbortWithStatus(http.StatusUnauthorized)
  937. assert.Equal(t, abortIndex, c.index)
  938. assert.Equal(t, http.StatusUnauthorized, c.Writer.Status())
  939. assert.Equal(t, http.StatusUnauthorized, w.Code)
  940. assert.True(t, c.IsAborted())
  941. }
  942. type testJSONAbortMsg struct {
  943. Foo string `json:"foo"`
  944. Bar string `json:"bar"`
  945. }
  946. func TestContextAbortWithStatusJSON(t *testing.T) {
  947. w := httptest.NewRecorder()
  948. c, _ := CreateTestContext(w)
  949. c.index = 4
  950. in := new(testJSONAbortMsg)
  951. in.Bar = "barValue"
  952. in.Foo = "fooValue"
  953. c.AbortWithStatusJSON(http.StatusUnsupportedMediaType, in)
  954. assert.Equal(t, abortIndex, c.index)
  955. assert.Equal(t, http.StatusUnsupportedMediaType, c.Writer.Status())
  956. assert.Equal(t, http.StatusUnsupportedMediaType, w.Code)
  957. assert.True(t, c.IsAborted())
  958. contentType := w.Header().Get("Content-Type")
  959. assert.Equal(t, "application/json; charset=utf-8", contentType)
  960. buf := new(bytes.Buffer)
  961. buf.ReadFrom(w.Body)
  962. jsonStringBody := buf.String()
  963. assert.Equal(t, fmt.Sprint(`{"foo":"fooValue","bar":"barValue"}`), jsonStringBody)
  964. }
  965. func TestContextError(t *testing.T) {
  966. c, _ := CreateTestContext(httptest.NewRecorder())
  967. assert.Empty(t, c.Errors)
  968. c.Error(errors.New("first error"))
  969. assert.Len(t, c.Errors, 1)
  970. assert.Equal(t, "Error #01: first error\n", c.Errors.String())
  971. c.Error(&Error{
  972. Err: errors.New("second error"),
  973. Meta: "some data 2",
  974. Type: ErrorTypePublic,
  975. })
  976. assert.Len(t, c.Errors, 2)
  977. assert.Equal(t, errors.New("first error"), c.Errors[0].Err)
  978. assert.Nil(t, c.Errors[0].Meta)
  979. assert.Equal(t, ErrorTypePrivate, c.Errors[0].Type)
  980. assert.Equal(t, errors.New("second error"), c.Errors[1].Err)
  981. assert.Equal(t, "some data 2", c.Errors[1].Meta)
  982. assert.Equal(t, ErrorTypePublic, c.Errors[1].Type)
  983. assert.Equal(t, c.Errors.Last(), c.Errors[1])
  984. defer func() {
  985. if recover() == nil {
  986. t.Error("didn't panic")
  987. }
  988. }()
  989. c.Error(nil)
  990. }
  991. func TestContextTypedError(t *testing.T) {
  992. c, _ := CreateTestContext(httptest.NewRecorder())
  993. c.Error(errors.New("externo 0")).SetType(ErrorTypePublic)
  994. c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate)
  995. for _, err := range c.Errors.ByType(ErrorTypePublic) {
  996. assert.Equal(t, ErrorTypePublic, err.Type)
  997. }
  998. for _, err := range c.Errors.ByType(ErrorTypePrivate) {
  999. assert.Equal(t, ErrorTypePrivate, err.Type)
  1000. }
  1001. assert.Equal(t, []string{"externo 0", "interno 0"}, c.Errors.Errors())
  1002. }
  1003. func TestContextAbortWithError(t *testing.T) {
  1004. w := httptest.NewRecorder()
  1005. c, _ := CreateTestContext(w)
  1006. c.AbortWithError(http.StatusUnauthorized, errors.New("bad input")).SetMeta("some input")
  1007. assert.Equal(t, http.StatusUnauthorized, w.Code)
  1008. assert.Equal(t, abortIndex, c.index)
  1009. assert.True(t, c.IsAborted())
  1010. }
  1011. func TestContextClientIP(t *testing.T) {
  1012. c, _ := CreateTestContext(httptest.NewRecorder())
  1013. c.Request, _ = http.NewRequest("POST", "/", nil)
  1014. c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ")
  1015. c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
  1016. c.Request.Header.Set("X-Appengine-Remote-Addr", "50.50.50.50")
  1017. c.Request.RemoteAddr = " 40.40.40.40:42123 "
  1018. assert.Equal(t, "20.20.20.20", c.ClientIP())
  1019. c.Request.Header.Del("X-Forwarded-For")
  1020. assert.Equal(t, "10.10.10.10", c.ClientIP())
  1021. c.Request.Header.Set("X-Forwarded-For", "30.30.30.30 ")
  1022. assert.Equal(t, "30.30.30.30", c.ClientIP())
  1023. c.Request.Header.Del("X-Forwarded-For")
  1024. c.Request.Header.Del("X-Real-IP")
  1025. c.engine.AppEngine = true
  1026. assert.Equal(t, "50.50.50.50", c.ClientIP())
  1027. c.Request.Header.Del("X-Appengine-Remote-Addr")
  1028. assert.Equal(t, "40.40.40.40", c.ClientIP())
  1029. // no port
  1030. c.Request.RemoteAddr = "50.50.50.50"
  1031. assert.Empty(t, c.ClientIP())
  1032. }
  1033. func TestContextContentType(t *testing.T) {
  1034. c, _ := CreateTestContext(httptest.NewRecorder())
  1035. c.Request, _ = http.NewRequest("POST", "/", nil)
  1036. c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  1037. assert.Equal(t, "application/json", c.ContentType())
  1038. }
  1039. func TestContextAutoBindJSON(t *testing.T) {
  1040. c, _ := CreateTestContext(httptest.NewRecorder())
  1041. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1042. c.Request.Header.Add("Content-Type", MIMEJSON)
  1043. var obj struct {
  1044. Foo string `json:"foo"`
  1045. Bar string `json:"bar"`
  1046. }
  1047. assert.NoError(t, c.Bind(&obj))
  1048. assert.Equal(t, "foo", obj.Bar)
  1049. assert.Equal(t, "bar", obj.Foo)
  1050. assert.Empty(t, c.Errors)
  1051. }
  1052. func TestContextBindWithJSON(t *testing.T) {
  1053. w := httptest.NewRecorder()
  1054. c, _ := CreateTestContext(w)
  1055. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1056. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  1057. var obj struct {
  1058. Foo string `json:"foo"`
  1059. Bar string `json:"bar"`
  1060. }
  1061. assert.NoError(t, c.BindJSON(&obj))
  1062. assert.Equal(t, "foo", obj.Bar)
  1063. assert.Equal(t, "bar", obj.Foo)
  1064. assert.Equal(t, 0, w.Body.Len())
  1065. }
  1066. func TestContextBindWithXML(t *testing.T) {
  1067. w := httptest.NewRecorder()
  1068. c, _ := CreateTestContext(w)
  1069. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(`<?xml version="1.0" encoding="UTF-8"?>
  1070. <root>
  1071. <foo>FOO</foo>
  1072. <bar>BAR</bar>
  1073. </root>`))
  1074. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  1075. var obj struct {
  1076. Foo string `xml:"foo"`
  1077. Bar string `xml:"bar"`
  1078. }
  1079. assert.NoError(t, c.BindXML(&obj))
  1080. assert.Equal(t, "FOO", obj.Foo)
  1081. assert.Equal(t, "BAR", obj.Bar)
  1082. assert.Equal(t, 0, w.Body.Len())
  1083. }
  1084. func TestContextBindWithQuery(t *testing.T) {
  1085. w := httptest.NewRecorder()
  1086. c, _ := CreateTestContext(w)
  1087. c.Request, _ = http.NewRequest("POST", "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused"))
  1088. var obj struct {
  1089. Foo string `form:"foo"`
  1090. Bar string `form:"bar"`
  1091. }
  1092. assert.NoError(t, c.BindQuery(&obj))
  1093. assert.Equal(t, "foo", obj.Bar)
  1094. assert.Equal(t, "bar", obj.Foo)
  1095. assert.Equal(t, 0, w.Body.Len())
  1096. }
  1097. func TestContextBadAutoBind(t *testing.T) {
  1098. w := httptest.NewRecorder()
  1099. c, _ := CreateTestContext(w)
  1100. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1101. c.Request.Header.Add("Content-Type", MIMEJSON)
  1102. var obj struct {
  1103. Foo string `json:"foo"`
  1104. Bar string `json:"bar"`
  1105. }
  1106. assert.False(t, c.IsAborted())
  1107. assert.Error(t, c.Bind(&obj))
  1108. c.Writer.WriteHeaderNow()
  1109. assert.Empty(t, obj.Bar)
  1110. assert.Empty(t, obj.Foo)
  1111. assert.Equal(t, http.StatusBadRequest, w.Code)
  1112. assert.True(t, c.IsAborted())
  1113. }
  1114. func TestContextAutoShouldBindJSON(t *testing.T) {
  1115. c, _ := CreateTestContext(httptest.NewRecorder())
  1116. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1117. c.Request.Header.Add("Content-Type", MIMEJSON)
  1118. var obj struct {
  1119. Foo string `json:"foo"`
  1120. Bar string `json:"bar"`
  1121. }
  1122. assert.NoError(t, c.ShouldBind(&obj))
  1123. assert.Equal(t, "foo", obj.Bar)
  1124. assert.Equal(t, "bar", obj.Foo)
  1125. assert.Empty(t, c.Errors)
  1126. }
  1127. func TestContextShouldBindWithJSON(t *testing.T) {
  1128. w := httptest.NewRecorder()
  1129. c, _ := CreateTestContext(w)
  1130. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1131. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  1132. var obj struct {
  1133. Foo string `json:"foo"`
  1134. Bar string `json:"bar"`
  1135. }
  1136. assert.NoError(t, c.ShouldBindJSON(&obj))
  1137. assert.Equal(t, "foo", obj.Bar)
  1138. assert.Equal(t, "bar", obj.Foo)
  1139. assert.Equal(t, 0, w.Body.Len())
  1140. }
  1141. func TestContextShouldBindWithXML(t *testing.T) {
  1142. w := httptest.NewRecorder()
  1143. c, _ := CreateTestContext(w)
  1144. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(`<?xml version="1.0" encoding="UTF-8"?>
  1145. <root>
  1146. <foo>FOO</foo>
  1147. <bar>BAR</bar>
  1148. </root>`))
  1149. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  1150. var obj struct {
  1151. Foo string `xml:"foo"`
  1152. Bar string `xml:"bar"`
  1153. }
  1154. assert.NoError(t, c.ShouldBindXML(&obj))
  1155. assert.Equal(t, "FOO", obj.Foo)
  1156. assert.Equal(t, "BAR", obj.Bar)
  1157. assert.Equal(t, 0, w.Body.Len())
  1158. }
  1159. func TestContextShouldBindWithQuery(t *testing.T) {
  1160. w := httptest.NewRecorder()
  1161. c, _ := CreateTestContext(w)
  1162. c.Request, _ = http.NewRequest("POST", "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused"))
  1163. var obj struct {
  1164. Foo string `form:"foo"`
  1165. Bar string `form:"bar"`
  1166. }
  1167. assert.NoError(t, c.ShouldBindQuery(&obj))
  1168. assert.Equal(t, "foo", obj.Bar)
  1169. assert.Equal(t, "bar", obj.Foo)
  1170. assert.Equal(t, 0, w.Body.Len())
  1171. }
  1172. func TestContextBadAutoShouldBind(t *testing.T) {
  1173. w := httptest.NewRecorder()
  1174. c, _ := CreateTestContext(w)
  1175. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1176. c.Request.Header.Add("Content-Type", MIMEJSON)
  1177. var obj struct {
  1178. Foo string `json:"foo"`
  1179. Bar string `json:"bar"`
  1180. }
  1181. assert.False(t, c.IsAborted())
  1182. assert.Error(t, c.ShouldBind(&obj))
  1183. assert.Empty(t, obj.Bar)
  1184. assert.Empty(t, obj.Foo)
  1185. assert.False(t, c.IsAborted())
  1186. }
  1187. func TestContextShouldBindBodyWith(t *testing.T) {
  1188. type typeA struct {
  1189. Foo string `json:"foo" xml:"foo" binding:"required"`
  1190. }
  1191. type typeB struct {
  1192. Bar string `json:"bar" xml:"bar" binding:"required"`
  1193. }
  1194. for _, tt := range []struct {
  1195. name string
  1196. bindingA, bindingB binding.BindingBody
  1197. bodyA, bodyB string
  1198. }{
  1199. {
  1200. name: "JSON & JSON",
  1201. bindingA: binding.JSON,
  1202. bindingB: binding.JSON,
  1203. bodyA: `{"foo":"FOO"}`,
  1204. bodyB: `{"bar":"BAR"}`,
  1205. },
  1206. {
  1207. name: "JSON & XML",
  1208. bindingA: binding.JSON,
  1209. bindingB: binding.XML,
  1210. bodyA: `{"foo":"FOO"}`,
  1211. bodyB: `<?xml version="1.0" encoding="UTF-8"?>
  1212. <root>
  1213. <bar>BAR</bar>
  1214. </root>`,
  1215. },
  1216. {
  1217. name: "XML & XML",
  1218. bindingA: binding.XML,
  1219. bindingB: binding.XML,
  1220. bodyA: `<?xml version="1.0" encoding="UTF-8"?>
  1221. <root>
  1222. <foo>FOO</foo>
  1223. </root>`,
  1224. bodyB: `<?xml version="1.0" encoding="UTF-8"?>
  1225. <root>
  1226. <bar>BAR</bar>
  1227. </root>`,
  1228. },
  1229. } {
  1230. t.Logf("testing: %s", tt.name)
  1231. // bodyA to typeA and typeB
  1232. {
  1233. w := httptest.NewRecorder()
  1234. c, _ := CreateTestContext(w)
  1235. c.Request, _ = http.NewRequest(
  1236. "POST", "http://example.com", bytes.NewBufferString(tt.bodyA),
  1237. )
  1238. // When it binds to typeA and typeB, it finds the body is
  1239. // not typeB but typeA.
  1240. objA := typeA{}
  1241. assert.NoError(t, c.ShouldBindBodyWith(&objA, tt.bindingA))
  1242. assert.Equal(t, typeA{"FOO"}, objA)
  1243. objB := typeB{}
  1244. assert.Error(t, c.ShouldBindBodyWith(&objB, tt.bindingB))
  1245. assert.NotEqual(t, typeB{"BAR"}, objB)
  1246. }
  1247. // bodyB to typeA and typeB
  1248. {
  1249. // When it binds to typeA and typeB, it finds the body is
  1250. // not typeA but typeB.
  1251. w := httptest.NewRecorder()
  1252. c, _ := CreateTestContext(w)
  1253. c.Request, _ = http.NewRequest(
  1254. "POST", "http://example.com", bytes.NewBufferString(tt.bodyB),
  1255. )
  1256. objA := typeA{}
  1257. assert.Error(t, c.ShouldBindBodyWith(&objA, tt.bindingA))
  1258. assert.NotEqual(t, typeA{"FOO"}, objA)
  1259. objB := typeB{}
  1260. assert.NoError(t, c.ShouldBindBodyWith(&objB, tt.bindingB))
  1261. assert.Equal(t, typeB{"BAR"}, objB)
  1262. }
  1263. }
  1264. }
  1265. func TestContextGolangContext(t *testing.T) {
  1266. c, _ := CreateTestContext(httptest.NewRecorder())
  1267. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1268. assert.NoError(t, c.Err())
  1269. assert.Nil(t, c.Done())
  1270. ti, ok := c.Deadline()
  1271. assert.Equal(t, ti, time.Time{})
  1272. assert.False(t, ok)
  1273. assert.Equal(t, c.Value(0), c.Request)
  1274. assert.Nil(t, c.Value("foo"))
  1275. c.Set("foo", "bar")
  1276. assert.Equal(t, "bar", c.Value("foo"))
  1277. assert.Nil(t, c.Value(1))
  1278. }
  1279. func TestWebsocketsRequired(t *testing.T) {
  1280. // Example request from spec: https://tools.ietf.org/html/rfc6455#section-1.2
  1281. c, _ := CreateTestContext(httptest.NewRecorder())
  1282. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  1283. c.Request.Header.Set("Host", "server.example.com")
  1284. c.Request.Header.Set("Upgrade", "websocket")
  1285. c.Request.Header.Set("Connection", "Upgrade")
  1286. c.Request.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")
  1287. c.Request.Header.Set("Origin", "http://example.com")
  1288. c.Request.Header.Set("Sec-WebSocket-Protocol", "chat, superchat")
  1289. c.Request.Header.Set("Sec-WebSocket-Version", "13")
  1290. assert.True(t, c.IsWebsocket())
  1291. // Normal request, no websocket required.
  1292. c, _ = CreateTestContext(httptest.NewRecorder())
  1293. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  1294. c.Request.Header.Set("Host", "server.example.com")
  1295. assert.False(t, c.IsWebsocket())
  1296. }
  1297. func TestGetRequestHeaderValue(t *testing.T) {
  1298. c, _ := CreateTestContext(httptest.NewRecorder())
  1299. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  1300. c.Request.Header.Set("Gin-Version", "1.0.0")
  1301. assert.Equal(t, "1.0.0", c.GetHeader("Gin-Version"))
  1302. assert.Empty(t, c.GetHeader("Connection"))
  1303. }
  1304. func TestContextGetRawData(t *testing.T) {
  1305. c, _ := CreateTestContext(httptest.NewRecorder())
  1306. body := bytes.NewBufferString("Fetch binary post data")
  1307. c.Request, _ = http.NewRequest("POST", "/", body)
  1308. c.Request.Header.Add("Content-Type", MIMEPOSTForm)
  1309. data, err := c.GetRawData()
  1310. assert.Nil(t, err)
  1311. assert.Equal(t, "Fetch binary post data", string(data))
  1312. }
  1313. func TestContextRenderDataFromReader(t *testing.T) {
  1314. w := httptest.NewRecorder()
  1315. c, _ := CreateTestContext(w)
  1316. body := "#!PNG some raw data"
  1317. reader := strings.NewReader(body)
  1318. contentLength := int64(len(body))
  1319. contentType := "image/png"
  1320. extraHeaders := map[string]string{"Content-Disposition": `attachment; filename="gopher.png"`}
  1321. c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)
  1322. assert.Equal(t, http.StatusOK, w.Code)
  1323. assert.Equal(t, body, w.Body.String())
  1324. assert.Equal(t, contentType, w.HeaderMap.Get("Content-Type"))
  1325. assert.Equal(t, fmt.Sprintf("%d", contentLength), w.HeaderMap.Get("Content-Length"))
  1326. assert.Equal(t, extraHeaders["Content-Disposition"], w.HeaderMap.Get("Content-Disposition"))
  1327. }
  1328. type TestResponseRecorder struct {
  1329. *httptest.ResponseRecorder
  1330. closeChannel chan bool
  1331. }
  1332. func (r *TestResponseRecorder) CloseNotify() <-chan bool {
  1333. return r.closeChannel
  1334. }
  1335. func (r *TestResponseRecorder) closeClient() {
  1336. r.closeChannel <- true
  1337. }
  1338. func CreateTestResponseRecorder() *TestResponseRecorder {
  1339. return &TestResponseRecorder{
  1340. httptest.NewRecorder(),
  1341. make(chan bool, 1),
  1342. }
  1343. }
  1344. func TestContextStream(t *testing.T) {
  1345. w := CreateTestResponseRecorder()
  1346. c, _ := CreateTestContext(w)
  1347. stopStream := true
  1348. c.Stream(func(w io.Writer) bool {
  1349. defer func() {
  1350. stopStream = false
  1351. }()
  1352. w.Write([]byte("test"))
  1353. return stopStream
  1354. })
  1355. assert.Equal(t, "testtest", w.Body.String())
  1356. }
  1357. func TestContextStreamWithClientGone(t *testing.T) {
  1358. w := CreateTestResponseRecorder()
  1359. c, _ := CreateTestContext(w)
  1360. c.Stream(func(writer io.Writer) bool {
  1361. defer func() {
  1362. w.closeClient()
  1363. }()
  1364. writer.Write([]byte("test"))
  1365. return true
  1366. })
  1367. assert.Equal(t, "test", w.Body.String())
  1368. }