Add Debug Mode (#422)

more info & better format

add debug mode

Co-authored-by: 6543 <6543@obermui.de>
Reviewed-on: https://gitea.com/gitea/go-sdk/pulls/422
Reviewed-by: Andrew Thornton <art27@cantab.net>
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
This commit is contained in:
6543 2020-09-19 15:23:16 +00:00 committed by Lunny Xiao
parent 3d7419dabb
commit 302993adb8

View file

@ -34,6 +34,7 @@ type Client struct {
password string password string
otp string otp string
sudo string sudo string
debug bool
client *http.Client client *http.Client
ctx context.Context ctx context.Context
serverVersion *version.Version serverVersion *version.Version
@ -135,7 +136,17 @@ func (c *Client) SetSudo(sudo string) {
c.sudo = sudo c.sudo = sudo
} }
// SetDebugMode is an option for NewClient to enable debug mode
func SetDebugMode() func(client *Client) {
return func(client *Client) {
client.debug = true
}
}
func (c *Client) getWebResponse(method, path string, body io.Reader) ([]byte, *Response, error) { func (c *Client) getWebResponse(method, path string, body io.Reader) ([]byte, *Response, error) {
if c.debug {
fmt.Printf("%s: %s\nBody: %v\n", method, c.url+path, body)
}
req, err := http.NewRequestWithContext(c.ctx, method, c.url+path, body) req, err := http.NewRequestWithContext(c.ctx, method, c.url+path, body)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
@ -147,10 +158,16 @@ func (c *Client) getWebResponse(method, path string, body io.Reader) ([]byte, *R
defer resp.Body.Close() defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body) data, err := ioutil.ReadAll(resp.Body)
if c.debug {
fmt.Printf("Response: %v\n\n", resp)
}
return data, &Response{resp}, nil return data, &Response{resp}, nil
} }
func (c *Client) doRequest(method, path string, header http.Header, body io.Reader) (*Response, error) { func (c *Client) doRequest(method, path string, header http.Header, body io.Reader) (*Response, error) {
if c.debug {
fmt.Printf("%s: %s\nHeader: %v\nBody: %s\n", method, c.url+"/api/v1"+path, header, body)
}
req, err := http.NewRequestWithContext(c.ctx, method, c.url+"/api/v1"+path, body) req, err := http.NewRequestWithContext(c.ctx, method, c.url+"/api/v1"+path, body)
if err != nil { if err != nil {
return nil, err return nil, err
@ -175,6 +192,9 @@ func (c *Client) doRequest(method, path string, header http.Header, body io.Read
if err != nil { if err != nil {
return nil, err return nil, err
} }
if c.debug {
fmt.Printf("Response: %v\n\n", resp)
}
return &Response{resp}, nil return &Response{resp}, nil
} }