context.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. package echo
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "encoding/xml"
  6. "fmt"
  7. "io"
  8. "mime/multipart"
  9. "net"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "path/filepath"
  14. "strings"
  15. )
  16. type (
  17. // Context represents the context of the current HTTP request. It holds request and
  18. // response objects, path, path parameters, data and registered handler.
  19. Context interface {
  20. // Request returns `*http.Request`.
  21. Request() *http.Request
  22. // SetRequest sets `*http.Request`.
  23. SetRequest(r *http.Request)
  24. // Response returns `*Response`.
  25. Response() *Response
  26. // IsTLS returns true if HTTP connection is TLS otherwise false.
  27. IsTLS() bool
  28. // IsWebSocket returns true if HTTP connection is WebSocket otherwise false.
  29. IsWebSocket() bool
  30. // Scheme returns the HTTP protocol scheme, `http` or `https`.
  31. Scheme() string
  32. // RealIP returns the client's network address based on `X-Forwarded-For`
  33. // or `X-Real-IP` request header.
  34. RealIP() string
  35. // Path returns the registered path for the handler.
  36. Path() string
  37. // SetPath sets the registered path for the handler.
  38. SetPath(p string)
  39. // Param returns path parameter by name.
  40. Param(name string) string
  41. // ParamNames returns path parameter names.
  42. ParamNames() []string
  43. // SetParamNames sets path parameter names.
  44. SetParamNames(names ...string)
  45. // ParamValues returns path parameter values.
  46. ParamValues() []string
  47. // SetParamValues sets path parameter values.
  48. SetParamValues(values ...string)
  49. // QueryParam returns the query param for the provided name.
  50. QueryParam(name string) string
  51. // QueryParams returns the query parameters as `url.Values`.
  52. QueryParams() url.Values
  53. // QueryString returns the URL query string.
  54. QueryString() string
  55. // FormValue returns the form field value for the provided name.
  56. FormValue(name string) string
  57. // FormParams returns the form parameters as `url.Values`.
  58. FormParams() (url.Values, error)
  59. // FormFile returns the multipart form file for the provided name.
  60. FormFile(name string) (*multipart.FileHeader, error)
  61. // MultipartForm returns the multipart form.
  62. MultipartForm() (*multipart.Form, error)
  63. // Cookie returns the named cookie provided in the request.
  64. Cookie(name string) (*http.Cookie, error)
  65. // SetCookie adds a `Set-Cookie` header in HTTP response.
  66. SetCookie(cookie *http.Cookie)
  67. // Cookies returns the HTTP cookies sent with the request.
  68. Cookies() []*http.Cookie
  69. // Get retrieves data from the context.
  70. Get(key string) interface{}
  71. // Set saves data in the context.
  72. Set(key string, val interface{})
  73. // Bind binds the request body into provided type `i`. The default binder
  74. // does it based on Content-Type header.
  75. Bind(i interface{}) error
  76. // Validate validates provided `i`. It is usually called after `Context#Bind()`.
  77. // Validator must be registered using `Echo#Validator`.
  78. Validate(i interface{}) error
  79. // Render renders a template with data and sends a text/html response with status
  80. // code. Renderer must be registered using `Echo.Renderer`.
  81. Render(code int, name string, data interface{}) error
  82. // HTML sends an HTTP response with status code.
  83. HTML(code int, html string) error
  84. // HTMLBlob sends an HTTP blob response with status code.
  85. HTMLBlob(code int, b []byte) error
  86. // String sends a string response with status code.
  87. String(code int, s string) error
  88. // JSON sends a JSON response with status code.
  89. JSON(code int, i interface{}) error
  90. // JSONPretty sends a pretty-print JSON with status code.
  91. JSONPretty(code int, i interface{}, indent string) error
  92. // JSONBlob sends a JSON blob response with status code.
  93. JSONBlob(code int, b []byte) error
  94. // JSONP sends a JSONP response with status code. It uses `callback` to construct
  95. // the JSONP payload.
  96. JSONP(code int, callback string, i interface{}) error
  97. // JSONPBlob sends a JSONP blob response with status code. It uses `callback`
  98. // to construct the JSONP payload.
  99. JSONPBlob(code int, callback string, b []byte) error
  100. // XML sends an XML response with status code.
  101. XML(code int, i interface{}) error
  102. // XMLPretty sends a pretty-print XML with status code.
  103. XMLPretty(code int, i interface{}, indent string) error
  104. // XMLBlob sends an XML blob response with status code.
  105. XMLBlob(code int, b []byte) error
  106. // Blob sends a blob response with status code and content type.
  107. Blob(code int, contentType string, b []byte) error
  108. // Stream sends a streaming response with status code and content type.
  109. Stream(code int, contentType string, r io.Reader) error
  110. // File sends a response with the content of the file.
  111. File(file string) error
  112. // Attachment sends a response as attachment, prompting client to save the
  113. // file.
  114. Attachment(file string, name string) error
  115. // Inline sends a response as inline, opening the file in the browser.
  116. Inline(file string, name string) error
  117. // NoContent sends a response with no body and a status code.
  118. NoContent(code int) error
  119. // Redirect redirects the request to a provided URL with status code.
  120. Redirect(code int, url string) error
  121. // Error invokes the registered HTTP error handler. Generally used by middleware.
  122. Error(err error)
  123. // Handler returns the matched handler by router.
  124. Handler() HandlerFunc
  125. // SetHandler sets the matched handler by router.
  126. SetHandler(h HandlerFunc)
  127. // Logger returns the `Logger` instance.
  128. Logger() Logger
  129. // Echo returns the `Echo` instance.
  130. Echo() *Echo
  131. // Reset resets the context after request completes. It must be called along
  132. // with `Echo#AcquireContext()` and `Echo#ReleaseContext()`.
  133. // See `Echo#ServeHTTP()`
  134. Reset(r *http.Request, w http.ResponseWriter)
  135. }
  136. context struct {
  137. request *http.Request
  138. response *Response
  139. path string
  140. pnames []string
  141. pvalues []string
  142. query url.Values
  143. handler HandlerFunc
  144. store Map
  145. echo *Echo
  146. }
  147. )
  148. const (
  149. defaultMemory = 32 << 20 // 32 MB
  150. indexPage = "index.html"
  151. )
  152. func (c *context) writeContentType(value string) {
  153. header := c.Response().Header()
  154. if header.Get(HeaderContentType) == "" {
  155. header.Set(HeaderContentType, value)
  156. }
  157. }
  158. func (c *context) Request() *http.Request {
  159. return c.request
  160. }
  161. func (c *context) SetRequest(r *http.Request) {
  162. c.request = r
  163. }
  164. func (c *context) Response() *Response {
  165. return c.response
  166. }
  167. func (c *context) IsTLS() bool {
  168. return c.request.TLS != nil
  169. }
  170. func (c *context) IsWebSocket() bool {
  171. upgrade := c.request.Header.Get(HeaderUpgrade)
  172. return upgrade == "websocket" || upgrade == "Websocket"
  173. }
  174. func (c *context) Scheme() string {
  175. // Can't use `r.Request.URL.Scheme`
  176. // See: https://groups.google.com/forum/#!topic/golang-nuts/pMUkBlQBDF0
  177. if c.IsTLS() {
  178. return "https"
  179. }
  180. if scheme := c.request.Header.Get(HeaderXForwardedProto); scheme != "" {
  181. return scheme
  182. }
  183. if scheme := c.request.Header.Get(HeaderXForwardedProtocol); scheme != "" {
  184. return scheme
  185. }
  186. if ssl := c.request.Header.Get(HeaderXForwardedSsl); ssl == "on" {
  187. return "https"
  188. }
  189. if scheme := c.request.Header.Get(HeaderXUrlScheme); scheme != "" {
  190. return scheme
  191. }
  192. return "http"
  193. }
  194. func (c *context) RealIP() string {
  195. ra := c.request.RemoteAddr
  196. if ip := c.request.Header.Get(HeaderXForwardedFor); ip != "" {
  197. ra = strings.Split(ip, ", ")[0]
  198. } else if ip := c.request.Header.Get(HeaderXRealIP); ip != "" {
  199. ra = ip
  200. } else {
  201. ra, _, _ = net.SplitHostPort(ra)
  202. }
  203. return ra
  204. }
  205. func (c *context) Path() string {
  206. return c.path
  207. }
  208. func (c *context) SetPath(p string) {
  209. c.path = p
  210. }
  211. func (c *context) Param(name string) string {
  212. for i, n := range c.pnames {
  213. if i < len(c.pvalues) {
  214. if n == name {
  215. return c.pvalues[i]
  216. }
  217. }
  218. }
  219. return ""
  220. }
  221. func (c *context) ParamNames() []string {
  222. return c.pnames
  223. }
  224. func (c *context) SetParamNames(names ...string) {
  225. c.pnames = names
  226. }
  227. func (c *context) ParamValues() []string {
  228. return c.pvalues[:len(c.pnames)]
  229. }
  230. func (c *context) SetParamValues(values ...string) {
  231. c.pvalues = values
  232. }
  233. func (c *context) QueryParam(name string) string {
  234. if c.query == nil {
  235. c.query = c.request.URL.Query()
  236. }
  237. return c.query.Get(name)
  238. }
  239. func (c *context) QueryParams() url.Values {
  240. if c.query == nil {
  241. c.query = c.request.URL.Query()
  242. }
  243. return c.query
  244. }
  245. func (c *context) QueryString() string {
  246. return c.request.URL.RawQuery
  247. }
  248. func (c *context) FormValue(name string) string {
  249. return c.request.FormValue(name)
  250. }
  251. func (c *context) FormParams() (url.Values, error) {
  252. if strings.HasPrefix(c.request.Header.Get(HeaderContentType), MIMEMultipartForm) {
  253. if err := c.request.ParseMultipartForm(defaultMemory); err != nil {
  254. return nil, err
  255. }
  256. } else {
  257. if err := c.request.ParseForm(); err != nil {
  258. return nil, err
  259. }
  260. }
  261. return c.request.Form, nil
  262. }
  263. func (c *context) FormFile(name string) (*multipart.FileHeader, error) {
  264. _, fh, err := c.request.FormFile(name)
  265. return fh, err
  266. }
  267. func (c *context) MultipartForm() (*multipart.Form, error) {
  268. err := c.request.ParseMultipartForm(defaultMemory)
  269. return c.request.MultipartForm, err
  270. }
  271. func (c *context) Cookie(name string) (*http.Cookie, error) {
  272. return c.request.Cookie(name)
  273. }
  274. func (c *context) SetCookie(cookie *http.Cookie) {
  275. http.SetCookie(c.Response(), cookie)
  276. }
  277. func (c *context) Cookies() []*http.Cookie {
  278. return c.request.Cookies()
  279. }
  280. func (c *context) Get(key string) interface{} {
  281. return c.store[key]
  282. }
  283. func (c *context) Set(key string, val interface{}) {
  284. if c.store == nil {
  285. c.store = make(Map)
  286. }
  287. c.store[key] = val
  288. }
  289. func (c *context) Bind(i interface{}) error {
  290. return c.echo.Binder.Bind(i, c)
  291. }
  292. func (c *context) Validate(i interface{}) error {
  293. if c.echo.Validator == nil {
  294. return ErrValidatorNotRegistered
  295. }
  296. return c.echo.Validator.Validate(i)
  297. }
  298. func (c *context) Render(code int, name string, data interface{}) (err error) {
  299. if c.echo.Renderer == nil {
  300. return ErrRendererNotRegistered
  301. }
  302. buf := new(bytes.Buffer)
  303. if err = c.echo.Renderer.Render(buf, name, data, c); err != nil {
  304. return
  305. }
  306. return c.HTMLBlob(code, buf.Bytes())
  307. }
  308. func (c *context) HTML(code int, html string) (err error) {
  309. return c.HTMLBlob(code, []byte(html))
  310. }
  311. func (c *context) HTMLBlob(code int, b []byte) (err error) {
  312. return c.Blob(code, MIMETextHTMLCharsetUTF8, b)
  313. }
  314. func (c *context) String(code int, s string) (err error) {
  315. return c.Blob(code, MIMETextPlainCharsetUTF8, []byte(s))
  316. }
  317. func (c *context) JSON(code int, i interface{}) (err error) {
  318. _, pretty := c.QueryParams()["pretty"]
  319. if c.echo.Debug || pretty {
  320. return c.JSONPretty(code, i, " ")
  321. }
  322. b, err := json.Marshal(i)
  323. if err != nil {
  324. return
  325. }
  326. return c.JSONBlob(code, b)
  327. }
  328. func (c *context) JSONPretty(code int, i interface{}, indent string) (err error) {
  329. b, err := json.MarshalIndent(i, "", indent)
  330. if err != nil {
  331. return
  332. }
  333. return c.JSONBlob(code, b)
  334. }
  335. func (c *context) JSONBlob(code int, b []byte) (err error) {
  336. return c.Blob(code, MIMEApplicationJSONCharsetUTF8, b)
  337. }
  338. func (c *context) JSONP(code int, callback string, i interface{}) (err error) {
  339. b, err := json.Marshal(i)
  340. if err != nil {
  341. return
  342. }
  343. return c.JSONPBlob(code, callback, b)
  344. }
  345. func (c *context) JSONPBlob(code int, callback string, b []byte) (err error) {
  346. c.writeContentType(MIMEApplicationJavaScriptCharsetUTF8)
  347. c.response.WriteHeader(code)
  348. if _, err = c.response.Write([]byte(callback + "(")); err != nil {
  349. return
  350. }
  351. if _, err = c.response.Write(b); err != nil {
  352. return
  353. }
  354. _, err = c.response.Write([]byte(");"))
  355. return
  356. }
  357. func (c *context) XML(code int, i interface{}) (err error) {
  358. _, pretty := c.QueryParams()["pretty"]
  359. if c.echo.Debug || pretty {
  360. return c.XMLPretty(code, i, " ")
  361. }
  362. b, err := xml.Marshal(i)
  363. if err != nil {
  364. return
  365. }
  366. return c.XMLBlob(code, b)
  367. }
  368. func (c *context) XMLPretty(code int, i interface{}, indent string) (err error) {
  369. b, err := xml.MarshalIndent(i, "", indent)
  370. if err != nil {
  371. return
  372. }
  373. return c.XMLBlob(code, b)
  374. }
  375. func (c *context) XMLBlob(code int, b []byte) (err error) {
  376. c.writeContentType(MIMEApplicationXMLCharsetUTF8)
  377. c.response.WriteHeader(code)
  378. if _, err = c.response.Write([]byte(xml.Header)); err != nil {
  379. return
  380. }
  381. _, err = c.response.Write(b)
  382. return
  383. }
  384. func (c *context) Blob(code int, contentType string, b []byte) (err error) {
  385. c.writeContentType(contentType)
  386. c.response.WriteHeader(code)
  387. _, err = c.response.Write(b)
  388. return
  389. }
  390. func (c *context) Stream(code int, contentType string, r io.Reader) (err error) {
  391. c.writeContentType(contentType)
  392. c.response.WriteHeader(code)
  393. _, err = io.Copy(c.response, r)
  394. return
  395. }
  396. func (c *context) File(file string) (err error) {
  397. f, err := os.Open(file)
  398. if err != nil {
  399. return NotFoundHandler(c)
  400. }
  401. defer f.Close()
  402. fi, _ := f.Stat()
  403. if fi.IsDir() {
  404. file = filepath.Join(file, indexPage)
  405. f, err = os.Open(file)
  406. if err != nil {
  407. return NotFoundHandler(c)
  408. }
  409. defer f.Close()
  410. if fi, err = f.Stat(); err != nil {
  411. return
  412. }
  413. }
  414. http.ServeContent(c.Response(), c.Request(), fi.Name(), fi.ModTime(), f)
  415. return
  416. }
  417. func (c *context) Attachment(file, name string) error {
  418. return c.contentDisposition(file, name, "attachment")
  419. }
  420. func (c *context) Inline(file, name string) error {
  421. return c.contentDisposition(file, name, "inline")
  422. }
  423. func (c *context) contentDisposition(file, name, dispositionType string) error {
  424. c.response.Header().Set(HeaderContentDisposition, fmt.Sprintf("%s; filename=%q", dispositionType, name))
  425. return c.File(file)
  426. }
  427. func (c *context) NoContent(code int) error {
  428. c.response.WriteHeader(code)
  429. return nil
  430. }
  431. func (c *context) Redirect(code int, url string) error {
  432. if code < 300 || code > 308 {
  433. return ErrInvalidRedirectCode
  434. }
  435. c.response.Header().Set(HeaderLocation, url)
  436. c.response.WriteHeader(code)
  437. return nil
  438. }
  439. func (c *context) Error(err error) {
  440. c.echo.HTTPErrorHandler(err, c)
  441. }
  442. func (c *context) Echo() *Echo {
  443. return c.echo
  444. }
  445. func (c *context) Handler() HandlerFunc {
  446. return c.handler
  447. }
  448. func (c *context) SetHandler(h HandlerFunc) {
  449. c.handler = h
  450. }
  451. func (c *context) Logger() Logger {
  452. return c.echo.Logger
  453. }
  454. func (c *context) Reset(r *http.Request, w http.ResponseWriter) {
  455. c.request = r
  456. c.response.reset(w)
  457. c.query = nil
  458. c.handler = NotFoundHandler
  459. c.store = nil
  460. c.path = ""
  461. c.pnames = nil
  462. // NOTE: Don't reset because it has to have length c.echo.maxParam at all times
  463. // c.pvalues = nil
  464. }