Path: blob/dev/pkg/protocols/offlinehttp/read_response.go
2070 views
package offlinehttp12import (3"bufio"4"errors"5"net/http"6"regexp"7"strings"8)910var noMinor = regexp.MustCompile(`HTTP/([0-9]) `)1112// readResponseFromString reads a raw http response from a string.13func readResponseFromString(data string) (*http.Response, error) {14// Check if "data" contains RFC compatible Request followed by a response15br := bufio.NewReader(strings.NewReader(data))16if req, err := http.ReadRequest(br); err == nil {17if resp, err := http.ReadResponse(br, req); err == nil {18return resp, nil19}20}2122// otherwise tries to patch known cases such as http minor version23var final string24if strings.HasPrefix(data, "HTTP/") {25final = addMinorVersionToHTTP(data)26} else {27lastIndex := strings.LastIndex(data, "HTTP/")28if lastIndex == -1 {29return nil, errors.New("malformed raw http response")30}31final = data[lastIndex:] // choose last http/ in case of it being later.3233final = addMinorVersionToHTTP(final)34}35return http.ReadResponse(bufio.NewReader(strings.NewReader(final)), nil)36}3738// addMinorVersionToHTTP tries to add a minor version to http status header39// fixing the compatibility issue with go standard library.40func addMinorVersionToHTTP(data string) string {41matches := noMinor.FindAllStringSubmatch(data, 1)42if len(matches) == 0 {43return data44}45if len(matches[0]) < 2 {46return data47}48replacedVersion := strings.Replace(matches[0][0], matches[0][1], matches[0][1]+".0", 1)49data = strings.Replace(data, matches[0][0], replacedVersion, 1)50return data51}525354