PageRenderTime 41ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/exp/connection.go

http://github.com/simonz05/godis
Go | 115 lines | 65 code | 24 blank | 26 comment | 18 complexity | c7b1f04c3a704fba0e92eeda5a1f160a MD5 | raw file
Possible License(s): BSD-3-Clause
  1. package redis
  2. import (
  3. "insmo.com/godis/bufin"
  4. "net"
  5. )
  6. var ConnSum = 0
  7. type Connection interface {
  8. Write(args ...interface{}) error
  9. Read() (*Reply, error)
  10. Close() error
  11. Sock() net.Conn
  12. }
  13. // Conn implements the Connection interface.
  14. type Conn struct {
  15. rbuf *bufin.Reader
  16. c net.Conn
  17. }
  18. // NewConn expects a network address and protocol.
  19. //
  20. // NewConn("127.0.0.1:6379", "tcp")
  21. //
  22. // or for a unix domain socket
  23. //
  24. // NewConn("/path/to/redis.sock", "unix")
  25. //
  26. // NewConn then returns a Conn struct which implements the Connection
  27. // interface. It's easy to use this interface to create your own
  28. // redis client or to simply talk to the redis database.
  29. func NewConn(addr, proto string, db int, password string) (*Conn, error) {
  30. conn, err := net.Dial(proto, addr)
  31. if err != nil {
  32. return nil, err
  33. }
  34. ConnSum++
  35. c := &Conn{bufin.NewReader(conn), conn}
  36. if password != "" {
  37. e := c.Write("AUTH", password)
  38. if e != nil {
  39. return nil, e
  40. }
  41. _, e = c.Read()
  42. if e != nil {
  43. return nil, e
  44. }
  45. }
  46. if db != 0 {
  47. e := c.Write("SELECT", db)
  48. if e != nil {
  49. return nil, e
  50. }
  51. _, e = c.Read()
  52. if e != nil {
  53. return nil, e
  54. }
  55. }
  56. return c, nil
  57. }
  58. // Read reads one reply of the socket connection. If there is no reply waiting
  59. // this method will block.
  60. // Returns either an error or a pointer to a Reply object.
  61. func (c *Conn) Read() (*Reply, error) {
  62. reply := Parse(c.rbuf)
  63. if reply.Err != nil {
  64. return nil, reply.Err
  65. }
  66. return reply, nil
  67. }
  68. // Write accepts any redis command and arbitrary list of arguments.
  69. //
  70. // Write("SET", "counter", 1)
  71. // Write("INCR", "counter")
  72. //
  73. // Write might return a net.Conn.Write error
  74. func (c *Conn) Write(args ...interface{}) error {
  75. _, e := c.c.Write(format(args...))
  76. if e != nil {
  77. return e
  78. }
  79. return nil
  80. }
  81. // Close is a simple helper method to close socket connection.
  82. func (c *Conn) Close() error {
  83. return c.c.Close()
  84. }
  85. // Sock returns the underlying net.Conn. You can use this connection as you
  86. // wish. An example could be to set a r/w deadline on the connection.
  87. //
  88. // Sock().SetDeadline(t)
  89. func (c *Conn) Sock() net.Conn {
  90. return c.c
  91. }