conn.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. pending int
  32. }
  33. // Dial connects to the Redis server at the given network and address.
  34. //
  35. // The returned connection is not thread-safe.
  36. func Dial(network, address string) (Conn, error) {
  37. netConn, err := net.Dial(network, address)
  38. if err != nil {
  39. return nil, err
  40. }
  41. return newConn(netConn), nil
  42. }
  43. // DialTimeout acts like Dial but takes a timeout. The timeout includes name
  44. // resolution, if required.
  45. func DialTimeout(network, address string, timeout time.Duration) (Conn, error) {
  46. netConn, err := net.DialTimeout(network, address, timeout)
  47. if err != nil {
  48. return nil, err
  49. }
  50. return newConn(netConn), nil
  51. }
  52. func newConn(netConn net.Conn) Conn {
  53. return &conn{
  54. conn: netConn,
  55. rw: bufio.ReadWriter{
  56. bufio.NewReader(netConn),
  57. bufio.NewWriter(netConn),
  58. },
  59. }
  60. }
  61. func (c *conn) Close() error {
  62. return c.conn.Close()
  63. }
  64. func (c *conn) Err() error {
  65. return c.err
  66. }
  67. func (c *conn) Do(cmd string, args ...interface{}) (interface{}, error) {
  68. if err := c.Send(cmd, args...); err != nil {
  69. return nil, err
  70. }
  71. var reply interface{}
  72. var err = c.err
  73. for c.pending > 0 && c.err == nil {
  74. var e error
  75. reply, e = c.Receive()
  76. if e != nil && err == nil {
  77. err = e
  78. }
  79. }
  80. return reply, err
  81. }
  82. func (c *conn) writeN(prefix byte, n int) error {
  83. c.scratch = append(c.scratch[0:0], prefix)
  84. c.scratch = strconv.AppendInt(c.scratch, int64(n), 10)
  85. c.scratch = append(c.scratch, "\r\n"...)
  86. _, err := c.rw.Write(c.scratch)
  87. return err
  88. }
  89. func (c *conn) writeString(s string) error {
  90. if err := c.writeN('$', len(s)); err != nil {
  91. return err
  92. }
  93. if _, err := c.rw.WriteString(s); err != nil {
  94. return err
  95. }
  96. _, err := c.rw.WriteString("\r\n")
  97. return err
  98. }
  99. func (c *conn) writeBytes(p []byte) error {
  100. if err := c.writeN('$', len(p)); err != nil {
  101. return err
  102. }
  103. if _, err := c.rw.Write(p); err != nil {
  104. return err
  105. }
  106. _, err := c.rw.WriteString("\r\n")
  107. return err
  108. }
  109. func (c *conn) readLine() ([]byte, error) {
  110. p, err := c.rw.ReadSlice('\n')
  111. if err == bufio.ErrBufferFull {
  112. return nil, errors.New("redigo: long response line")
  113. }
  114. if err != nil {
  115. return nil, err
  116. }
  117. i := len(p) - 2
  118. if i < 0 || p[i] != '\r' {
  119. return nil, errors.New("redigo: bad response line terminator")
  120. }
  121. return p[:i], nil
  122. }
  123. func (c *conn) parseReply() (interface{}, error) {
  124. line, err := c.readLine()
  125. if err != nil {
  126. return nil, err
  127. }
  128. if len(line) == 0 {
  129. return nil, errors.New("redigo: short response line")
  130. }
  131. switch line[0] {
  132. case '+':
  133. return string(line[1:]), nil
  134. case '-':
  135. return Error(string(line[1:])), nil
  136. case ':':
  137. n, err := strconv.ParseInt(string(line[1:]), 10, 64)
  138. if err != nil {
  139. return nil, err
  140. }
  141. return n, nil
  142. case '$':
  143. n, err := strconv.Atoi(string(line[1:]))
  144. if err != nil || n < 0 {
  145. return nil, err
  146. }
  147. p := make([]byte, n)
  148. _, err = io.ReadFull(c.rw, p)
  149. if err != nil {
  150. return nil, err
  151. }
  152. line, err := c.readLine()
  153. if err != nil {
  154. return nil, err
  155. }
  156. if len(line) != 0 {
  157. return nil, errors.New("redigo: bad bulk format")
  158. }
  159. return p, nil
  160. case '*':
  161. n, err := strconv.Atoi(string(line[1:]))
  162. if err != nil || n < 0 {
  163. return nil, err
  164. }
  165. r := make([]interface{}, n)
  166. for i := range r {
  167. r[i], err = c.parseReply()
  168. if err != nil {
  169. return nil, err
  170. }
  171. }
  172. return r, nil
  173. }
  174. return nil, errors.New("redigo: unpexected response line")
  175. }
  176. // Send sends a command for the server without waiting for a reply.
  177. func (c *conn) Send(cmd string, args ...interface{}) error {
  178. if c.err != nil {
  179. return c.err
  180. }
  181. c.err = c.writeN('*', 1+len(args))
  182. if c.err != nil {
  183. return c.err
  184. }
  185. c.err = c.writeString(cmd)
  186. if c.err != nil {
  187. return c.err
  188. }
  189. for _, arg := range args {
  190. switch arg := arg.(type) {
  191. case string:
  192. c.err = c.writeString(arg)
  193. case []byte:
  194. c.err = c.writeBytes(arg)
  195. case nil:
  196. c.err = c.writeString("")
  197. default:
  198. var buf bytes.Buffer
  199. fmt.Fprint(&buf, arg)
  200. c.err = c.writeBytes(buf.Bytes())
  201. }
  202. if c.err != nil {
  203. return c.err
  204. }
  205. }
  206. c.pending += 1
  207. return nil
  208. }
  209. func (c *conn) Receive() (interface{}, error) {
  210. c.pending -= 1
  211. c.err = c.rw.Flush()
  212. if c.err != nil {
  213. return nil, c.err
  214. }
  215. v, err := c.parseReply()
  216. if err != nil {
  217. c.err = err
  218. } else if e, ok := v.(Error); ok {
  219. err = e
  220. }
  221. return v, err
  222. }