context_test.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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. "html/template"
  9. "mime/multipart"
  10. "net/http"
  11. "net/http/httptest"
  12. "strings"
  13. "testing"
  14. "time"
  15. "github.com/manucorporat/sse"
  16. "github.com/stretchr/testify/assert"
  17. )
  18. // Unit tests TODO
  19. // func (c *Context) File(filepath string) {
  20. // func (c *Context) Negotiate(code int, config Negotiate) {
  21. // BAD case: func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
  22. // test that information is not leaked when reusing Contexts (using the Pool)
  23. func createMultipartRequest() *http.Request {
  24. boundary := "--testboundary"
  25. body := new(bytes.Buffer)
  26. mw := multipart.NewWriter(body)
  27. defer mw.Close()
  28. must(mw.SetBoundary(boundary))
  29. must(mw.WriteField("foo", "bar"))
  30. must(mw.WriteField("bar", "foo"))
  31. must(mw.WriteField("bar", "foo2"))
  32. must(mw.WriteField("array", "first"))
  33. must(mw.WriteField("array", "second"))
  34. req, err := http.NewRequest("POST", "/", body)
  35. must(err)
  36. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  37. return req
  38. }
  39. func must(err error) {
  40. if err != nil {
  41. panic(err.Error())
  42. }
  43. }
  44. func TestContextReset(t *testing.T) {
  45. router := New()
  46. c := router.allocateContext()
  47. assert.Equal(t, c.engine, router)
  48. c.index = 2
  49. c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()}
  50. c.Params = Params{Param{}}
  51. c.Error(errors.New("test"))
  52. c.Set("foo", "bar")
  53. c.reset()
  54. assert.False(t, c.IsAborted())
  55. assert.Nil(t, c.Keys)
  56. assert.Nil(t, c.Accepted)
  57. assert.Len(t, c.Errors, 0)
  58. assert.Empty(t, c.Errors.Errors())
  59. assert.Empty(t, c.Errors.ByType(ErrorTypeAny))
  60. assert.Len(t, c.Params, 0)
  61. assert.EqualValues(t, c.index, -1)
  62. assert.Equal(t, c.Writer.(*responseWriter), &c.writermem)
  63. }
  64. func TestContextHandlers(t *testing.T) {
  65. c, _, _ := CreateTestContext()
  66. assert.Nil(t, c.handlers)
  67. assert.Nil(t, c.handlers.Last())
  68. c.handlers = HandlersChain{}
  69. assert.NotNil(t, c.handlers)
  70. assert.Nil(t, c.handlers.Last())
  71. f := func(c *Context) {}
  72. g := func(c *Context) {}
  73. c.handlers = HandlersChain{f}
  74. compareFunc(t, f, c.handlers.Last())
  75. c.handlers = HandlersChain{f, g}
  76. compareFunc(t, g, c.handlers.Last())
  77. }
  78. // TestContextSetGet tests that a parameter is set correctly on the
  79. // current context and can be retrieved using Get.
  80. func TestContextSetGet(t *testing.T) {
  81. c, _, _ := CreateTestContext()
  82. c.Set("foo", "bar")
  83. value, err := c.Get("foo")
  84. assert.Equal(t, value, "bar")
  85. assert.True(t, err)
  86. value, err = c.Get("foo2")
  87. assert.Nil(t, value)
  88. assert.False(t, err)
  89. assert.Equal(t, c.MustGet("foo"), "bar")
  90. assert.Panics(t, func() { c.MustGet("no_exist") })
  91. }
  92. func TestContextSetGetValues(t *testing.T) {
  93. c, _, _ := CreateTestContext()
  94. c.Set("string", "this is a string")
  95. c.Set("int32", int32(-42))
  96. c.Set("int64", int64(42424242424242))
  97. c.Set("uint64", uint64(42))
  98. c.Set("float32", float32(4.2))
  99. c.Set("float64", 4.2)
  100. var a interface{} = 1
  101. c.Set("intInterface", a)
  102. assert.Exactly(t, c.MustGet("string").(string), "this is a string")
  103. assert.Exactly(t, c.MustGet("int32").(int32), int32(-42))
  104. assert.Exactly(t, c.MustGet("int64").(int64), int64(42424242424242))
  105. assert.Exactly(t, c.MustGet("uint64").(uint64), uint64(42))
  106. assert.Exactly(t, c.MustGet("float32").(float32), float32(4.2))
  107. assert.Exactly(t, c.MustGet("float64").(float64), 4.2)
  108. assert.Exactly(t, c.MustGet("intInterface").(int), 1)
  109. }
  110. func TestContextCopy(t *testing.T) {
  111. c, _, _ := CreateTestContext()
  112. c.index = 2
  113. c.Request, _ = http.NewRequest("POST", "/hola", nil)
  114. c.handlers = HandlersChain{func(c *Context) {}}
  115. c.Params = Params{Param{Key: "foo", Value: "bar"}}
  116. c.Set("foo", "bar")
  117. cp := c.Copy()
  118. assert.Nil(t, cp.handlers)
  119. assert.Nil(t, cp.writermem.ResponseWriter)
  120. assert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))
  121. assert.Equal(t, cp.Request, c.Request)
  122. assert.Equal(t, cp.index, abortIndex)
  123. assert.Equal(t, cp.Keys, c.Keys)
  124. assert.Equal(t, cp.engine, c.engine)
  125. assert.Equal(t, cp.Params, c.Params)
  126. }
  127. func TestContextHandlerName(t *testing.T) {
  128. c, _, _ := CreateTestContext()
  129. c.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}
  130. assert.Regexp(t, "^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$", c.HandlerName())
  131. }
  132. func handlerNameTest(c *Context) {
  133. }
  134. func TestContextQuery(t *testing.T) {
  135. c, _, _ := CreateTestContext()
  136. c.Request, _ = http.NewRequest("GET", "http://example.com/?foo=bar&page=10", nil)
  137. assert.Equal(t, c.DefaultQuery("foo", "none"), "bar")
  138. assert.Equal(t, c.Query("foo"), "bar")
  139. assert.Empty(t, c.PostForm("foo"))
  140. assert.Equal(t, c.DefaultQuery("page", "0"), "10")
  141. assert.Equal(t, c.Query("page"), "10")
  142. assert.Empty(t, c.PostForm("page"))
  143. assert.Equal(t, c.DefaultQuery("NoKey", "nada"), "nada")
  144. assert.Empty(t, c.Query("NoKey"))
  145. assert.Empty(t, c.PostForm("NoKey"))
  146. }
  147. func TestContextQueryAndPostForm(t *testing.T) {
  148. c, _, _ := CreateTestContext()
  149. body := bytes.NewBufferString("foo=bar&page=11&both=POST&foo=second")
  150. c.Request, _ = http.NewRequest("POST", "/?both=GET&id=main&id=omit&array[]=first&array[]=second", body)
  151. c.Request.Header.Add("Content-Type", MIMEPOSTForm)
  152. assert.Equal(t, c.DefaultPostForm("foo", "none"), "bar")
  153. assert.Equal(t, c.PostForm("foo"), "bar")
  154. assert.Empty(t, c.Query("foo"))
  155. assert.Equal(t, c.DefaultPostForm("page", "0"), "11")
  156. assert.Equal(t, c.PostForm("page"), "11")
  157. assert.Equal(t, c.Query("page"), "")
  158. assert.Equal(t, c.PostForm("both"), "POST")
  159. assert.Equal(t, c.Query("both"), "GET")
  160. assert.Equal(t, c.DefaultPostForm("id", "000"), "000")
  161. assert.Equal(t, c.Query("id"), "main")
  162. assert.Empty(t, c.PostForm("id"))
  163. assert.Equal(t, c.DefaultPostForm("NoKey", "nada"), "nada")
  164. assert.Empty(t, c.PostForm("NoKey"))
  165. assert.Empty(t, c.Query("NoKey"))
  166. var obj struct {
  167. Foo string `form:"foo"`
  168. ID string `form:"id"`
  169. Page string `form:"page"`
  170. Both string `form:"both"`
  171. Array []string `form:"array[]"`
  172. }
  173. assert.NoError(t, c.Bind(&obj))
  174. assert.Equal(t, obj.Foo, "bar")
  175. assert.Equal(t, obj.ID, "main")
  176. assert.Equal(t, obj.Page, "11")
  177. assert.Equal(t, obj.Both, "POST")
  178. assert.Equal(t, obj.Array, []string{"first", "second"})
  179. }
  180. func TestContextPostFormMultipart(t *testing.T) {
  181. c, _, _ := CreateTestContext()
  182. c.Request = createMultipartRequest()
  183. var obj struct {
  184. Foo string `form:"foo"`
  185. Bar string `form:"bar"`
  186. Array []string `form:"array"`
  187. }
  188. assert.NoError(t, c.Bind(&obj))
  189. assert.Equal(t, obj.Bar, "foo")
  190. assert.Equal(t, obj.Foo, "bar")
  191. assert.Equal(t, obj.Array, []string{"first", "second"})
  192. assert.Empty(t, c.Query("foo"))
  193. assert.Empty(t, c.Query("bar"))
  194. assert.Equal(t, c.PostForm("foo"), "bar")
  195. assert.Equal(t, c.PostForm("array"), "first")
  196. assert.Equal(t, c.PostForm("bar"), "foo")
  197. }
  198. func TestContextSetCookie(t *testing.T) {
  199. c, _, _ := CreateTestContext()
  200. c.SetCookie("user", "gin", 1, "/", "localhost", true, true)
  201. c.Request, _ = http.NewRequest("GET", "/set", nil)
  202. assert.Equal(t, c.Writer.Header().Get("Set-Cookie"), "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure")
  203. }
  204. func TestContextGetCookie(t *testing.T) {
  205. c, _, _ := CreateTestContext()
  206. c.Request, _ = http.NewRequest("GET", "/get", nil)
  207. c.Request.Header.Set("Cookie", "user=gin")
  208. cookie, _ := c.GetCookie("user")
  209. assert.Equal(t, cookie, "gin")
  210. }
  211. // Tests that the response is serialized as JSON
  212. // and Content-Type is set to application/json
  213. func TestContextRenderJSON(t *testing.T) {
  214. c, w, _ := CreateTestContext()
  215. c.JSON(201, H{"foo": "bar"})
  216. assert.Equal(t, w.Code, 201)
  217. assert.Equal(t, w.Body.String(), "{\"foo\":\"bar\"}\n")
  218. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  219. }
  220. // Tests that the response is serialized as JSON
  221. // we change the content-type before
  222. func TestContextRenderAPIJSON(t *testing.T) {
  223. c, w, _ := CreateTestContext()
  224. c.Header("Content-Type", "application/vnd.api+json")
  225. c.JSON(201, H{"foo": "bar"})
  226. assert.Equal(t, w.Code, 201)
  227. assert.Equal(t, w.Body.String(), "{\"foo\":\"bar\"}\n")
  228. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/vnd.api+json")
  229. }
  230. // Tests that the response is serialized as JSON
  231. // and Content-Type is set to application/json
  232. func TestContextRenderIndentedJSON(t *testing.T) {
  233. c, w, _ := CreateTestContext()
  234. c.IndentedJSON(201, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  235. assert.Equal(t, w.Code, 201)
  236. assert.Equal(t, w.Body.String(), "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}")
  237. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  238. }
  239. // Tests that the response executes the templates
  240. // and responds with Content-Type set to text/html
  241. func TestContextRenderHTML(t *testing.T) {
  242. c, w, router := CreateTestContext()
  243. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  244. router.SetHTMLTemplate(templ)
  245. c.HTML(201, "t", H{"name": "alexandernyquist"})
  246. assert.Equal(t, w.Code, 201)
  247. assert.Equal(t, w.Body.String(), "Hello alexandernyquist")
  248. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  249. }
  250. // TestContextXML tests that the response is serialized as XML
  251. // and Content-Type is set to application/xml
  252. func TestContextRenderXML(t *testing.T) {
  253. c, w, _ := CreateTestContext()
  254. c.XML(201, H{"foo": "bar"})
  255. assert.Equal(t, w.Code, 201)
  256. assert.Equal(t, w.Body.String(), "<map><foo>bar</foo></map>")
  257. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8")
  258. }
  259. // TestContextString tests that the response is returned
  260. // with Content-Type set to text/plain
  261. func TestContextRenderString(t *testing.T) {
  262. c, w, _ := CreateTestContext()
  263. c.String(201, "test %s %d", "string", 2)
  264. assert.Equal(t, w.Code, 201)
  265. assert.Equal(t, w.Body.String(), "test string 2")
  266. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  267. }
  268. // TestContextString tests that the response is returned
  269. // with Content-Type set to text/html
  270. func TestContextRenderHTMLString(t *testing.T) {
  271. c, w, _ := CreateTestContext()
  272. c.Header("Content-Type", "text/html; charset=utf-8")
  273. c.String(201, "<html>%s %d</html>", "string", 3)
  274. assert.Equal(t, w.Code, 201)
  275. assert.Equal(t, w.Body.String(), "<html>string 3</html>")
  276. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  277. }
  278. // TestContextData tests that the response can be written from `bytesting`
  279. // with specified MIME type
  280. func TestContextRenderData(t *testing.T) {
  281. c, w, _ := CreateTestContext()
  282. c.Data(201, "text/csv", []byte(`foo,bar`))
  283. assert.Equal(t, w.Code, 201)
  284. assert.Equal(t, w.Body.String(), "foo,bar")
  285. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv")
  286. }
  287. func TestContextRenderSSE(t *testing.T) {
  288. c, w, _ := CreateTestContext()
  289. c.SSEvent("float", 1.5)
  290. c.Render(-1, sse.Event{
  291. Id: "123",
  292. Data: "text",
  293. })
  294. c.SSEvent("chat", H{
  295. "foo": "bar",
  296. "bar": "foo",
  297. })
  298. 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))
  299. }
  300. func TestContextRenderFile(t *testing.T) {
  301. c, w, _ := CreateTestContext()
  302. c.Request, _ = http.NewRequest("GET", "/", nil)
  303. c.File("./gin.go")
  304. assert.Equal(t, w.Code, 200)
  305. assert.Contains(t, w.Body.String(), "func New() *Engine {")
  306. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  307. }
  308. func TestContextHeaders(t *testing.T) {
  309. c, _, _ := CreateTestContext()
  310. c.Header("Content-Type", "text/plain")
  311. c.Header("X-Custom", "value")
  312. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/plain")
  313. assert.Equal(t, c.Writer.Header().Get("X-Custom"), "value")
  314. c.Header("Content-Type", "text/html")
  315. c.Header("X-Custom", "")
  316. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/html")
  317. _, exist := c.Writer.Header()["X-Custom"]
  318. assert.False(t, exist)
  319. }
  320. // TODO
  321. func TestContextRenderRedirectWithRelativePath(t *testing.T) {
  322. c, w, _ := CreateTestContext()
  323. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  324. assert.Panics(t, func() { c.Redirect(299, "/new_path") })
  325. assert.Panics(t, func() { c.Redirect(309, "/new_path") })
  326. c.Redirect(302, "/path")
  327. c.Writer.WriteHeaderNow()
  328. assert.Equal(t, w.Code, 302)
  329. assert.Equal(t, w.Header().Get("Location"), "/path")
  330. }
  331. func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
  332. c, w, _ := CreateTestContext()
  333. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  334. c.Redirect(302, "http://google.com")
  335. c.Writer.WriteHeaderNow()
  336. assert.Equal(t, w.Code, 302)
  337. assert.Equal(t, w.Header().Get("Location"), "http://google.com")
  338. }
  339. func TestContextNegotiationFormat(t *testing.T) {
  340. c, _, _ := CreateTestContext()
  341. c.Request, _ = http.NewRequest("POST", "", nil)
  342. assert.Panics(t, func() { c.NegotiateFormat() })
  343. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  344. assert.Equal(t, c.NegotiateFormat(MIMEHTML, MIMEJSON), MIMEHTML)
  345. }
  346. func TestContextNegotiationFormatWithAccept(t *testing.T) {
  347. c, _, _ := CreateTestContext()
  348. c.Request, _ = http.NewRequest("POST", "/", nil)
  349. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  350. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEXML)
  351. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEHTML)
  352. assert.Equal(t, c.NegotiateFormat(MIMEJSON), "")
  353. }
  354. func TestContextNegotiationFormatCustum(t *testing.T) {
  355. c, _, _ := CreateTestContext()
  356. c.Request, _ = http.NewRequest("POST", "/", nil)
  357. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  358. c.Accepted = nil
  359. c.SetAccepted(MIMEJSON, MIMEXML)
  360. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  361. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEXML)
  362. assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON)
  363. }
  364. func TestContextIsAborted(t *testing.T) {
  365. c, _, _ := CreateTestContext()
  366. assert.False(t, c.IsAborted())
  367. c.Abort()
  368. assert.True(t, c.IsAborted())
  369. c.Next()
  370. assert.True(t, c.IsAborted())
  371. c.index++
  372. assert.True(t, c.IsAborted())
  373. }
  374. // TestContextData tests that the response can be written from `bytesting`
  375. // with specified MIME type
  376. func TestContextAbortWithStatus(t *testing.T) {
  377. c, w, _ := CreateTestContext()
  378. c.index = 4
  379. c.AbortWithStatus(401)
  380. c.Writer.WriteHeaderNow()
  381. assert.Equal(t, c.index, abortIndex)
  382. assert.Equal(t, c.Writer.Status(), 401)
  383. assert.Equal(t, w.Code, 401)
  384. assert.True(t, c.IsAborted())
  385. }
  386. func TestContextError(t *testing.T) {
  387. c, _, _ := CreateTestContext()
  388. assert.Empty(t, c.Errors)
  389. c.Error(errors.New("first error"))
  390. assert.Len(t, c.Errors, 1)
  391. assert.Equal(t, c.Errors.String(), "Error #01: first error\n")
  392. c.Error(&Error{
  393. Err: errors.New("second error"),
  394. Meta: "some data 2",
  395. Type: ErrorTypePublic,
  396. })
  397. assert.Len(t, c.Errors, 2)
  398. assert.Equal(t, c.Errors[0].Err, errors.New("first error"))
  399. assert.Nil(t, c.Errors[0].Meta)
  400. assert.Equal(t, c.Errors[0].Type, ErrorTypePrivate)
  401. assert.Equal(t, c.Errors[1].Err, errors.New("second error"))
  402. assert.Equal(t, c.Errors[1].Meta, "some data 2")
  403. assert.Equal(t, c.Errors[1].Type, ErrorTypePublic)
  404. assert.Equal(t, c.Errors.Last(), c.Errors[1])
  405. }
  406. func TestContextTypedError(t *testing.T) {
  407. c, _, _ := CreateTestContext()
  408. c.Error(errors.New("externo 0")).SetType(ErrorTypePublic)
  409. c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate)
  410. for _, err := range c.Errors.ByType(ErrorTypePublic) {
  411. assert.Equal(t, err.Type, ErrorTypePublic)
  412. }
  413. for _, err := range c.Errors.ByType(ErrorTypePrivate) {
  414. assert.Equal(t, err.Type, ErrorTypePrivate)
  415. }
  416. assert.Equal(t, c.Errors.Errors(), []string{"externo 0", "interno 0"})
  417. }
  418. func TestContextAbortWithError(t *testing.T) {
  419. c, w, _ := CreateTestContext()
  420. c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")
  421. c.Writer.WriteHeaderNow()
  422. assert.Equal(t, w.Code, 401)
  423. assert.Equal(t, c.index, abortIndex)
  424. assert.True(t, c.IsAborted())
  425. }
  426. func TestContextClientIP(t *testing.T) {
  427. c, _, _ := CreateTestContext()
  428. c.Request, _ = http.NewRequest("POST", "/", nil)
  429. c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ")
  430. c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
  431. c.Request.RemoteAddr = " 40.40.40.40:42123 "
  432. assert.Equal(t, c.ClientIP(), "10.10.10.10")
  433. c.Request.Header.Del("X-Real-IP")
  434. assert.Equal(t, c.ClientIP(), "20.20.20.20")
  435. c.Request.Header.Set("X-Forwarded-For", "30.30.30.30 ")
  436. assert.Equal(t, c.ClientIP(), "30.30.30.30")
  437. c.Request.Header.Del("X-Forwarded-For")
  438. assert.Equal(t, c.ClientIP(), "40.40.40.40")
  439. }
  440. func TestContextContentType(t *testing.T) {
  441. c, _, _ := CreateTestContext()
  442. c.Request, _ = http.NewRequest("POST", "/", nil)
  443. c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  444. assert.Equal(t, c.ContentType(), "application/json")
  445. }
  446. func TestContextAutoBindJSON(t *testing.T) {
  447. c, _, _ := CreateTestContext()
  448. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  449. c.Request.Header.Add("Content-Type", MIMEJSON)
  450. var obj struct {
  451. Foo string `json:"foo"`
  452. Bar string `json:"bar"`
  453. }
  454. assert.NoError(t, c.Bind(&obj))
  455. assert.Equal(t, obj.Bar, "foo")
  456. assert.Equal(t, obj.Foo, "bar")
  457. assert.Empty(t, c.Errors)
  458. }
  459. func TestContextBindWithJSON(t *testing.T) {
  460. c, w, _ := CreateTestContext()
  461. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  462. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  463. var obj struct {
  464. Foo string `json:"foo"`
  465. Bar string `json:"bar"`
  466. }
  467. assert.NoError(t, c.BindJSON(&obj))
  468. assert.Equal(t, obj.Bar, "foo")
  469. assert.Equal(t, obj.Foo, "bar")
  470. assert.Equal(t, w.Body.Len(), 0)
  471. }
  472. func TestContextBadAutoBind(t *testing.T) {
  473. c, w, _ := CreateTestContext()
  474. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  475. c.Request.Header.Add("Content-Type", MIMEJSON)
  476. var obj struct {
  477. Foo string `json:"foo"`
  478. Bar string `json:"bar"`
  479. }
  480. assert.False(t, c.IsAborted())
  481. assert.Error(t, c.Bind(&obj))
  482. c.Writer.WriteHeaderNow()
  483. assert.Empty(t, obj.Bar)
  484. assert.Empty(t, obj.Foo)
  485. assert.Equal(t, w.Code, 400)
  486. assert.True(t, c.IsAborted())
  487. }
  488. func TestContextGolangContext(t *testing.T) {
  489. c, _, _ := CreateTestContext()
  490. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  491. assert.NoError(t, c.Err())
  492. assert.Nil(t, c.Done())
  493. ti, ok := c.Deadline()
  494. assert.Equal(t, ti, time.Time{})
  495. assert.False(t, ok)
  496. assert.Equal(t, c.Value(0), c.Request)
  497. assert.Nil(t, c.Value("foo"))
  498. c.Set("foo", "bar")
  499. assert.Equal(t, c.Value("foo"), "bar")
  500. assert.Nil(t, c.Value(1))
  501. }