From 0af39effe16ac60b09d0fa1a5656270934c569a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edmond=20Dant=C3=A8s?= <18221510672@139.com> Date: Tue, 25 Jun 2024 20:04:17 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- request.go | 42 +++++++++++++++++++++++++++--------------- utils.go | 4 ---- 2 files changed, 27 insertions(+), 19 deletions(-) diff --git a/request.go b/request.go index 9333a61..50efae0 100644 --- a/request.go +++ b/request.go @@ -6,6 +6,7 @@ import ( "crypto/tls" "encoding/json" "io" + "io/ioutil" "net/http" "net/url" "reflect" @@ -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 @@ -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 - //} } } diff --git a/utils.go b/utils.go index 4d64887..40704d8 100644 --- a/utils.go +++ b/utils.go @@ -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 }