Context

包路径: github.com/caicloud/nirvana/service

在 Nirvana 中,Context 用于传递请求的上下文。Context 中包含 HTTP 的 Request 和 ResponseWriter。可是使用 service 包的 HTTPContextFrom() 方法获得 HTTP Context。HTTP Context 相关接口如下:

  1. // ValueContainer contains values from a request.
  2. type ValueContainer interface {
  3. // Path returns path value by key.
  4. Path(key string) (string, bool)
  5. // Query returns value from query string.
  6. Query(key string) ([]string, bool)
  7. // Header returns value by header key.
  8. Header(key string) ([]string, bool)
  9. // Form returns value from request. It is valid when
  10. // http "Content-Type" is "application/x-www-form-urlencoded"
  11. // or "multipart/form-data".
  12. Form(key string) ([]string, bool)
  13. // File returns a file reader when "Content-Type" is "multipart/form-data".
  14. File(key string) (multipart.File, bool)
  15. // Body returns a reader to read data from request body.
  16. // The reader only can read once.
  17. Body() (reader io.ReadCloser, contentType string, ok bool)
  18. }
  19. // ResponseWriter extends http.ResponseWriter.
  20. type ResponseWriter interface {
  21. http.ResponseWriter
  22. // HeaderWritable can check whether WriteHeader() has
  23. // been called. If the method returns false, you should
  24. // not recall WriteHeader().
  25. HeaderWritable() bool
  26. // StatusCode returns status code.
  27. StatusCode() int
  28. // ContentLength returns the length of written content.
  29. ContentLength() int
  30. }
  31. // HTTPContext describes an http context.
  32. type HTTPContext interface {
  33. Request() *http.Request
  34. ResponseWriter() ResponseWriter
  35. ValueContainer() ValueContainer
  36. RoutePath() string
  37. }

Nirvana 框架会为每个请求构建这样的 HTTPContext。如有必要,可以通过这些接口拿到与请求相关的所有数据。

在一个请求路由匹配成功后,Nirvana 会把对应的 HTTPContext 传递给中间件,然后由中间件调用链继续传递。最终经由 ContextPrefab 传递给业务函数。

中间件不应该修改 HTTPContext,除非您明确知道如何修改。