Skip to content

Commit

Permalink
优化
Browse files Browse the repository at this point in the history
  • Loading branch information
shijl0925 committed Jun 25, 2024
1 parent f740c4d commit 0af39ef
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 19 deletions.
42 changes: 27 additions & 15 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"crypto/tls"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
Expand Down Expand Up @@ -169,6 +170,14 @@ func (r *Requester) NewRequest(ctx context.Context, method, endpoint string, opt
}

func (r *Requester) Do(req *http.Request, v interface{}) (*http.Response, error) {
isText := false
if v != nil {
if _, ok := v.(*string); ok {
req.Header.Set("Accept", "text/plain")
isText = true
}
}

resp, err := r.client.Do(req)
if err != nil {
return resp, err
Expand All @@ -190,22 +199,25 @@ func (r *Requester) Do(req *http.Request, v interface{}) (*http.Response, error)
return nil, err
}
} else {
var body []byte
body, err = io.ReadAll(resp.Body)
if err != nil {
// even though there was an error, we still return the response
// in case the caller wants to inspect it further
return resp, err
if isText {
var body []byte
body, err = io.ReadAll(resp.Body)
if err != nil {
// even though there was an error, we still return the response
// in case the caller wants to inspect it further
return resp, err
}
body = RemoveMagicPrefixLine(body)

w := v.(*string)
*w = strings.Trim(string(body), "\"\n")

} else {
io.CopyN(ioutil.Discard, resp.Body, 5)
if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
return resp, err
}
}
body = RemoveMagicPrefixLine(body)
//log.Println(string(body))

err = json.Unmarshal(body, v)

//io.CopyN(ioutil.Discard, resp.Body, 5)
//if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
// return resp, err
//}
}
}

Expand Down
4 changes: 0 additions & 4 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,6 @@ func RemoveMagicPrefixLine(body []byte) []byte {
body = body[5:]
}

if bytes.Equal(body, []byte("ok")) || bytes.Equal(body, []byte("ok\n")) {
return []byte("\"ok\"\n")
}

return body
}

Expand Down

0 comments on commit 0af39ef

Please sign in to comment.