diff --git a/parser.go b/parser.go index caaf49c..3e590bf 100644 --- a/parser.go +++ b/parser.go @@ -8,8 +8,7 @@ import ( "strings" ) -func parseRequest(conn io.ReadCloser) (*Request, error) { - r := bufio.NewReader(conn) +func parseRequest(r *bufio.Reader) (*Request, error) { // first line of redis request should be: // *CRLF line, err := r.ReadString('\n') @@ -21,7 +20,7 @@ func parseRequest(conn io.ReadCloser) (*Request, error) { // Multiline request: if line[0] == '*' { - if _, err := fmt.Sscanf(line, "*%d\r", &argsCount); err != nil { + if _, err := fmt.Sscanf(line, "*%d\r\n", &argsCount); err != nil { return nil, malformed("*", line) } // All next lines are pairs of: @@ -43,7 +42,6 @@ func parseRequest(conn io.ReadCloser) (*Request, error) { return &Request{ Name: strings.ToLower(string(firstArg)), Args: args, - Body: conn, }, nil } @@ -59,7 +57,6 @@ func parseRequest(conn io.ReadCloser) (*Request, error) { return &Request{ Name: strings.ToLower(string(fields[0])), Args: args, - Body: conn, }, nil } @@ -71,7 +68,7 @@ func readArgument(r *bufio.Reader) ([]byte, error) { return nil, malformed("$", line) } var argSize int - if _, err := fmt.Sscanf(line, "$%d\r", &argSize); err != nil { + if _, err := fmt.Sscanf(line, "$%d\r\n", &argSize); err != nil { return nil, malformed("$", line) } diff --git a/request.go b/request.go index 4888e69..dd16048 100644 --- a/request.go +++ b/request.go @@ -1,16 +1,12 @@ package redis -import ( - "io" - "strconv" -) +import "strconv" type Request struct { Name string Args [][]byte Host string ClientChan chan struct{} - Body io.ReadCloser } func (r *Request) HasArgument(index int) bool { diff --git a/server.go b/server.go index c4a4131..e7d0c90 100644 --- a/server.go +++ b/server.go @@ -5,7 +5,9 @@ package redis import ( + "bufio" "fmt" + "golang.org/x/net/netutil" "io" "io/ioutil" "net" @@ -19,7 +21,8 @@ type Server struct { methods map[string]HandlerFn } -func (srv *Server) ListenAndServe() error { +// ListenAndServe receives an argument maxConnection, which limit max connection it can accept simultaneous, passing maxConnection <= 0 means no limit. +func (srv *Server) ListenAndServe(maxConnection int) error { addr := srv.Addr if srv.Proto == "" { srv.Proto = "tcp" @@ -33,6 +36,9 @@ func (srv *Server) ListenAndServe() error { if e != nil { return e } + if maxConnection > 0 { + l = netutil.LimitListener(l, maxConnection) + } return srv.Serve(l) } @@ -88,8 +94,9 @@ func (srv *Server) ServeClient(conn net.Conn) (err error) { clientAddr = co.RemoteAddr().String() } + br := bufio.NewReader(conn) for { - request, err := parseRequest(conn) + request, err := parseRequest(br) if err != nil { return err }