github.com/wangyougui/gf/v2@v2.6.5/net/gclient/gclient_response.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 package gclient 8 9 import ( 10 "bytes" 11 "io" 12 "net/http" 13 14 "github.com/wangyougui/gf/v2/internal/intlog" 15 ) 16 17 // Response is the struct for client request response. 18 type Response struct { 19 *http.Response // Response is the underlying http.Response object of certain request. 20 request *http.Request // Request is the underlying http.Request object of certain request. 21 requestBody []byte // The body bytes of certain request, only available in Dump feature. 22 cookies map[string]string // Response cookies, which are only parsed once. 23 } 24 25 // initCookie initializes the cookie map attribute of Response. 26 func (r *Response) initCookie() { 27 if r.cookies == nil { 28 r.cookies = make(map[string]string) 29 // Response might be nil. 30 if r.Response != nil { 31 for _, v := range r.Cookies() { 32 r.cookies[v.Name] = v.Value 33 } 34 } 35 } 36 } 37 38 // GetCookie retrieves and returns the cookie value of specified `key`. 39 func (r *Response) GetCookie(key string) string { 40 r.initCookie() 41 return r.cookies[key] 42 } 43 44 // GetCookieMap retrieves and returns a copy of current cookie values map. 45 func (r *Response) GetCookieMap() map[string]string { 46 r.initCookie() 47 m := make(map[string]string, len(r.cookies)) 48 for k, v := range r.cookies { 49 m[k] = v 50 } 51 return m 52 } 53 54 // ReadAll retrieves and returns the response content as []byte. 55 func (r *Response) ReadAll() []byte { 56 // Response might be nil. 57 if r == nil || r.Response == nil { 58 return []byte{} 59 } 60 body, err := io.ReadAll(r.Response.Body) 61 if err != nil { 62 intlog.Errorf(r.request.Context(), `%+v`, err) 63 return nil 64 } 65 return body 66 } 67 68 // ReadAllString retrieves and returns the response content as string. 69 func (r *Response) ReadAllString() string { 70 return string(r.ReadAll()) 71 } 72 73 // SetBodyContent overwrites response content with custom one. 74 func (r *Response) SetBodyContent(content []byte) { 75 buffer := bytes.NewBuffer(content) 76 r.Body = io.NopCloser(buffer) 77 r.ContentLength = int64(buffer.Len()) 78 } 79 80 // Close closes the response when it will never be used. 81 func (r *Response) Close() error { 82 if r == nil || r.Response == nil { 83 return nil 84 } 85 return r.Response.Body.Close() 86 }