conn.go 5.3 KB

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