context_test.go 51 KB

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