diff options
Diffstat (limited to 'spartan/response.go')
-rw-r--r-- | spartan/response.go | 36 |
1 files changed, 34 insertions, 2 deletions
diff --git a/spartan/response.go b/spartan/response.go index edc1db6..bd906e0 100644 --- a/spartan/response.go +++ b/spartan/response.go @@ -1,8 +1,11 @@ package spartan import ( + "bufio" "bytes" + "errors" "io" + "strconv" "sync" "tildegit.org/tjp/gus" @@ -37,7 +40,7 @@ func Redirect(url string) *gus.Response { func ClientError(err error) *gus.Response { return &gus.Response{ Status: StatusClientError, - Meta: err.Error(), + Meta: err.Error(), } } @@ -45,10 +48,39 @@ func ClientError(err error) *gus.Response { func ServerError(err error) *gus.Response { return &gus.Response{ Status: StatusServerError, - Meta: err.Error(), + Meta: err.Error(), } } +// InvalidResponseHeaderLine indicates a malformed spartan response line. +var InvalidResponseHeaderLine = errors.New("Invalid response header line.") + +// InvalidResponseLineEnding indicates that a spartan response header didn't end with "\r\n". +var InvalidResponseLineEnding = errors.New("Invalid response line ending.") + +func ParseResponse(rdr io.Reader) (*gus.Response, error) { + bufrdr := bufio.NewReader(rdr) + + hdrLine, err := bufrdr.ReadString('\n') + if err != nil { + return nil, InvalidResponseLineEnding + } + if len(hdrLine) < 2 { + return nil, InvalidResponseHeaderLine + } + + status, err := strconv.Atoi(string(hdrLine[0])) + if err != nil || hdrLine[1] != ' ' || hdrLine[len(hdrLine)-2:] != "\r\n" { + return nil, InvalidResponseHeaderLine + } + + return &gus.Response{ + Status: gus.Status(status), + Meta: hdrLine[2 : len(hdrLine)-2], + Body: bufrdr, + }, nil +} + // NewResponseReader builds a reader for a response. func NewResponseReader(response *gus.Response) gus.ResponseReader { return &responseReader{ |