/server/stamped.go

http://github.com/petar/GoHTTP · Go · 94 lines · 71 code · 15 blank · 8 comment · 8 complexity · a49cc41df34cf5b55149dfa76cfb84d2 MD5 · raw file

  1. // Copyright 2009 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. package server
  5. import (
  6. "bufio"
  7. "net"
  8. "sync"
  9. "time"
  10. "net/http"
  11. "net/http/httputil"
  12. )
  13. // StampedServerConn is an httputil.ServerConn which additionally
  14. // keeps track of the last time the connection performed I/O.
  15. type StampedServerConn struct {
  16. *httputil.ServerConn
  17. stamp int64
  18. lk sync.Mutex
  19. }
  20. func NewStampedServerConn(c net.Conn, r *bufio.Reader) *StampedServerConn {
  21. return &StampedServerConn{
  22. ServerConn: http.NewServerConn(c, r),
  23. stamp: time.Nanoseconds(),
  24. }
  25. }
  26. func (ssc *StampedServerConn) touch() {
  27. ssc.lk.Lock()
  28. defer ssc.lk.Unlock()
  29. ssc.stamp = time.Nanoseconds()
  30. }
  31. func (ssc *StampedServerConn) GetStamp() int64 {
  32. ssc.lk.Lock()
  33. defer ssc.lk.Unlock()
  34. return ssc.stamp
  35. }
  36. func (ssc *StampedServerConn) Read() (req *http.Request, err error) {
  37. ssc.touch()
  38. defer ssc.touch()
  39. return ssc.ServerConn.Read()
  40. }
  41. func (ssc *StampedServerConn) Write(req *http.Request, resp *http.Response) (err error) {
  42. ssc.touch()
  43. defer ssc.touch()
  44. return ssc.ServerConn.Write(req, resp)
  45. }
  46. // StampedClientConn is an httputil.ClientConn which additionally
  47. // keeps track of the last time the connection performed I/O.
  48. type StampedClientConn struct {
  49. *httputil.ClientConn
  50. stamp int64
  51. lk sync.Mutex
  52. }
  53. func NewStampedClientConn(c net.Conn, r *bufio.Reader) *StampedClientConn {
  54. return &StampedClientConn{
  55. ClientConn: http.NewClientConn(c, r),
  56. stamp: time.Nanoseconds(),
  57. }
  58. }
  59. func (scc *StampedClientConn) touch() {
  60. scc.lk.Lock()
  61. defer scc.lk.Unlock()
  62. scc.stamp = time.Nanoseconds()
  63. }
  64. func (scc *StampedClientConn) GetStamp() int64 {
  65. scc.lk.Lock()
  66. defer scc.lk.Unlock()
  67. return scc.stamp
  68. }
  69. func (scc *StampedClientConn) Read(req *http.Request) (resp *http.Response, err error) {
  70. scc.touch()
  71. defer scc.touch()
  72. return scc.ClientConn.Read(req)
  73. }
  74. func (scc *StampedClientConn) Write(req *http.Request) (err error) {
  75. scc.touch()
  76. defer scc.touch()
  77. return scc.ClientConn.Write(req)
  78. }
  79. // XXX: Should ClientConn.Do be wrapped as well?