conn.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. // Copyright 2012 Gary Burd
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package redis
  15. import (
  16. "bufio"
  17. "bytes"
  18. "errors"
  19. "fmt"
  20. "io"
  21. "net"
  22. "strconv"
  23. "time"
  24. )
  25. // conn is the low-level implementation of Conn
  26. type conn struct {
  27. rw bufio.ReadWriter
  28. conn net.Conn
  29. err error
  30. scratch []byte
  31. }
  32. // Dial connects to the Redis server at the given network and address.
  33. //
  34. // The returned connection is not thread-safe.
  35. func Dial(network, address string) (Conn, error) {
  36. netConn, err := net.Dial(network, address)
  37. if err != nil {
  38. return nil, err
  39. }
  40. return newConn(netConn), nil
  41. }
  42. // DialTimeout acts like Dial but takes a timeout. The timeout includes name
  43. // resolution, if required.
  44. func DialTimeout(network, address string, timeout time.Duration) (Conn, error) {
  45. netConn, err := net.DialTimeout(network, address, timeout)
  46. if err != nil {
  47. return nil, err
  48. }
  49. return newConn(netConn), nil
  50. }
  51. func newConn(netConn net.Conn) Conn {
  52. return &conn{
  53. conn: netConn,
  54. rw: bufio.ReadWriter{
  55. bufio.NewReader(netConn),
  56. bufio.NewWriter(netConn),
  57. },
  58. }
  59. }
  60. // Close closes the connection.
  61. func (c *conn) Close() error {
  62. return c.conn.Close()
  63. }
  64. // Err returns the permanent error for this connection.
  65. func (c *conn) Err() error {
  66. return c.err
  67. }
  68. // Do sends a command to the server and returns the received reply.
  69. func (c *conn) Do(cmd string, args ...interface{}) (interface{}, error) {
  70. if err := c.Send(cmd, args...); err != nil {
  71. return nil, err
  72. }
  73. return c.Receive()
  74. }
  75. func (c *conn) writeN(prefix byte, n int) error {
  76. c.scratch = append(c.scratch[0:0], prefix)
  77. c.scratch = strconv.AppendInt(c.scratch, int64(n), 10)
  78. c.scratch = append(c.scratch, "\r\n"...)
  79. _, err := c.rw.Write(c.scratch)
  80. return err
  81. }
  82. func (c *conn) writeString(s string) error {
  83. if err := c.writeN('$', len(s)); err != nil {
  84. return err
  85. }
  86. if _, err := c.rw.WriteString(s); err != nil {
  87. return err
  88. }
  89. _, err := c.rw.WriteString("\r\n")
  90. return err
  91. }
  92. func (c *conn) writeBytes(p []byte) error {
  93. if err := c.writeN('$', len(p)); err != nil {
  94. return err
  95. }
  96. if _, err := c.rw.Write(p); err != nil {
  97. return err
  98. }
  99. _, err := c.rw.WriteString("\r\n")
  100. return err
  101. }
  102. func (c *conn) readLine() ([]byte, error) {
  103. p, err := c.rw.ReadSlice('\n')
  104. if err == bufio.ErrBufferFull {
  105. return nil, errors.New("redigo: long response line")
  106. }
  107. if err != nil {
  108. return nil, err
  109. }
  110. i := len(p) - 2
  111. if i < 0 || p[i] != '\r' {
  112. return nil, errors.New("redigo: bad response line terminator")
  113. }
  114. return p[:i], nil
  115. }
  116. func (c *conn) parseReply() (interface{}, error) {
  117. line, err := c.readLine()
  118. if err != nil {
  119. return nil, err
  120. }
  121. if len(line) == 0 {
  122. return nil, errors.New("redigo: short response line")
  123. }
  124. switch line[0] {
  125. case '+':
  126. return string(line[1:]), nil
  127. case '-':
  128. return Error(string(line[1:])), nil
  129. case ':':
  130. n, err := strconv.ParseInt(string(line[1:]), 10, 64)
  131. if err != nil {
  132. return nil, err
  133. }
  134. return n, nil
  135. case '$':
  136. n, err := strconv.Atoi(string(line[1:]))
  137. if err != nil || n < 0 {
  138. return nil, err
  139. }
  140. p := make([]byte, n)
  141. _, err = io.ReadFull(c.rw, p)
  142. if err != nil {
  143. return nil, err
  144. }
  145. line, err := c.readLine()
  146. if err != nil {
  147. return nil, err
  148. }
  149. if len(line) != 0 {
  150. return nil, errors.New("redigo: bad bulk format")
  151. }
  152. return p, nil
  153. case '*':
  154. n, err := strconv.Atoi(string(line[1:]))
  155. if err != nil || n < 0 {
  156. return nil, err
  157. }
  158. r := make([]interface{}, n)
  159. for i := range r {
  160. r[i], err = c.parseReply()
  161. if err != nil {
  162. return nil, err
  163. }
  164. }
  165. return r, nil
  166. }
  167. return nil, errors.New("redigo: unpexected response line")
  168. }
  169. // Send sends a command for the server without waiting for a reply.
  170. func (c *conn) Send(cmd string, args ...interface{}) error {
  171. if c.err != nil {
  172. return c.err
  173. }
  174. c.err = c.writeN('*', 1+len(args))
  175. if c.err != nil {
  176. return c.err
  177. }
  178. c.err = c.writeString(cmd)
  179. if c.err != nil {
  180. return c.err
  181. }
  182. for _, arg := range args {
  183. switch arg := arg.(type) {
  184. case string:
  185. c.err = c.writeString(arg)
  186. case []byte:
  187. c.err = c.writeBytes(arg)
  188. case nil:
  189. c.err = c.writeString("")
  190. default:
  191. var buf bytes.Buffer
  192. fmt.Fprint(&buf, arg)
  193. c.err = c.writeBytes(buf.Bytes())
  194. }
  195. if c.err != nil {
  196. return c.err
  197. }
  198. }
  199. return nil
  200. }
  201. // Receive receives a single reply from the server
  202. func (c *conn) Receive() (interface{}, error) {
  203. c.err = c.rw.Flush()
  204. if c.err != nil {
  205. return nil, c.err
  206. }
  207. v, err := c.parseReply()
  208. if err != nil {
  209. c.err = err
  210. } else if e, ok := v.(Error); ok {
  211. err = e
  212. }
  213. return v, err
  214. }