diff options
author | tjpcc <tjp@ctrl-c.club> | 2023-04-29 17:38:26 -0600 |
---|---|---|
committer | tjpcc <tjp@ctrl-c.club> | 2023-04-29 17:38:26 -0600 |
commit | 9e09825537e4ae91119987f979ec4272d1727a2e (patch) | |
tree | be76862e51439bc24aab2bf5e6685ae73f9f0c39 /spartan/response.go | |
parent | fcea3099cb2dce7f953e46389f83b6f9b58bef86 (diff) |
initial spartan client support
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{ |