go17.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build go1.7
  5. package http2
  6. import (
  7. "context"
  8. "net"
  9. "net/http"
  10. "net/http/httptrace"
  11. "time"
  12. )
  13. type contextContext interface {
  14. context.Context
  15. }
  16. func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx contextContext, cancel func()) {
  17. ctx, cancel = context.WithCancel(context.Background())
  18. ctx = context.WithValue(ctx, http.LocalAddrContextKey, c.LocalAddr())
  19. if hs := opts.baseConfig(); hs != nil {
  20. ctx = context.WithValue(ctx, http.ServerContextKey, hs)
  21. }
  22. return
  23. }
  24. func contextWithCancel(ctx contextContext) (_ contextContext, cancel func()) {
  25. return context.WithCancel(ctx)
  26. }
  27. func requestWithContext(req *http.Request, ctx contextContext) *http.Request {
  28. return req.WithContext(ctx)
  29. }
  30. type clientTrace httptrace.ClientTrace
  31. func reqContext(r *http.Request) context.Context { return r.Context() }
  32. func setResponseUncompressed(res *http.Response) { res.Uncompressed = true }
  33. func traceGotConn(req *http.Request, cc *ClientConn) {
  34. trace := httptrace.ContextClientTrace(req.Context())
  35. if trace == nil || trace.GotConn == nil {
  36. return
  37. }
  38. ci := httptrace.GotConnInfo{Conn: cc.tconn}
  39. cc.mu.Lock()
  40. ci.Reused = cc.nextStreamID > 1
  41. ci.WasIdle = len(cc.streams) == 0 && ci.Reused
  42. if ci.WasIdle && !cc.lastActive.IsZero() {
  43. ci.IdleTime = time.Now().Sub(cc.lastActive)
  44. }
  45. cc.mu.Unlock()
  46. trace.GotConn(ci)
  47. }
  48. func traceWroteHeaders(trace *clientTrace) {
  49. if trace != nil && trace.WroteHeaders != nil {
  50. trace.WroteHeaders()
  51. }
  52. }
  53. func traceGot100Continue(trace *clientTrace) {
  54. if trace != nil && trace.Got100Continue != nil {
  55. trace.Got100Continue()
  56. }
  57. }
  58. func traceWait100Continue(trace *clientTrace) {
  59. if trace != nil && trace.Wait100Continue != nil {
  60. trace.Wait100Continue()
  61. }
  62. }
  63. func traceWroteRequest(trace *clientTrace, err error) {
  64. if trace != nil && trace.WroteRequest != nil {
  65. trace.WroteRequest(httptrace.WroteRequestInfo{Err: err})
  66. }
  67. }
  68. func traceFirstResponseByte(trace *clientTrace) {
  69. if trace != nil && trace.GotFirstResponseByte != nil {
  70. trace.GotFirstResponseByte()
  71. }
  72. }
  73. func requestTrace(req *http.Request) *clientTrace {
  74. trace := httptrace.ContextClientTrace(req.Context())
  75. return (*clientTrace)(trace)
  76. }