Skip to content

Commit

Permalink
Remove usages of deprecated io/ioutil
Browse files Browse the repository at this point in the history
io/ioutil has been deprecated since go1.16, and its functionality
has been moved to io and os packages.
  • Loading branch information
segevda committed Mar 9, 2023
1 parent 1578007 commit 6400907
Show file tree
Hide file tree
Showing 7 changed files with 59 additions and 66 deletions.
6 changes: 3 additions & 3 deletions README.md
Expand Up @@ -265,7 +265,7 @@ resp, err := client.R().
Post("https://myapp.com/login")

// POST of raw bytes for file upload. For example: upload file to Dropbox
fileBytes, _ := ioutil.ReadFile("/Users/jeeva/mydocument.pdf")
fileBytes, _ := os.ReadFile("/Users/jeeva/mydocument.pdf")

// See we are not setting content-type header, since go-resty automatically detects Content-Type for you
resp, err := client.R().
Expand Down Expand Up @@ -383,8 +383,8 @@ client.XMLUnmarshal
#### Using io.Reader

```go
profileImgBytes, _ := ioutil.ReadFile("/Users/jeeva/test-img.png")
notesBytes, _ := ioutil.ReadFile("/Users/jeeva/text-file.txt")
profileImgBytes, _ := os.ReadFile("/Users/jeeva/test-img.png")
notesBytes, _ := os.ReadFile("/Users/jeeva/text-file.txt")

// Create a Resty Client
client := resty.New()
Expand Down
52 changes: 26 additions & 26 deletions client.go
Expand Up @@ -14,10 +14,10 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"net/http"
"net/url"
"os"
"reflect"
"regexp"
"strings"
Expand Down Expand Up @@ -126,29 +126,29 @@ type Client struct {
// value when `SetAuthToken` option is used.
HeaderAuthorizationKey string

jsonEscapeHTML bool
setContentLength bool
closeConnection bool
notParseResponse bool
trace bool
debugBodySizeLimit int64
outputDirectory string
scheme string
log Logger
httpClient *http.Client
proxyURL *url.URL
beforeRequest []RequestMiddleware
udBeforeRequest []RequestMiddleware
udBeforeRequestLock sync.RWMutex
preReqHook PreRequestHook
successHooks []SuccessHook
afterResponse []ResponseMiddleware
afterResponseLock sync.RWMutex
requestLog RequestLogCallback
responseLog ResponseLogCallback
errorHooks []ErrorHook
invalidHooks []ErrorHook
panicHooks []ErrorHook
jsonEscapeHTML bool
setContentLength bool
closeConnection bool
notParseResponse bool
trace bool
debugBodySizeLimit int64
outputDirectory string
scheme string
log Logger
httpClient *http.Client
proxyURL *url.URL
beforeRequest []RequestMiddleware
udBeforeRequest []RequestMiddleware
udBeforeRequestLock sync.RWMutex
preReqHook PreRequestHook
successHooks []SuccessHook
afterResponse []ResponseMiddleware
afterResponseLock sync.RWMutex
requestLog RequestLogCallback
responseLog ResponseLogCallback
errorHooks []ErrorHook
invalidHooks []ErrorHook
panicHooks []ErrorHook
}

// User type is to hold an username and password information
Expand Down Expand Up @@ -797,7 +797,7 @@ func (c *Client) SetCertificates(certs ...tls.Certificate) *Client {
//
// client.SetRootCertificate("/path/to/root/pemFile.pem")
func (c *Client) SetRootCertificate(pemFilePath string) *Client {
rootPemData, err := ioutil.ReadFile(pemFilePath)
rootPemData, err := os.ReadFile(pemFilePath)
if err != nil {
c.log.Errorf("%v", err)
return c
Expand Down Expand Up @@ -1060,7 +1060,7 @@ func (c *Client) execute(req *Request) (*Response, error) {
}
}

if response.body, err = ioutil.ReadAll(body); err != nil {
if response.body, err = io.ReadAll(body); err != nil {
response.setReceivedAt()
return response, err
}
Expand Down
15 changes: 8 additions & 7 deletions client_test.go
Expand Up @@ -9,10 +9,11 @@ import (
"crypto/tls"
"errors"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"strconv"
Expand Down Expand Up @@ -205,7 +206,7 @@ func TestClientSetRootCertificateNotExists(t *testing.T) {

func TestClientSetRootCertificateFromString(t *testing.T) {
client := dc()
rootPemData, err := ioutil.ReadFile(filepath.Join(getTestDataPath(), "sample-root.pem"))
rootPemData, err := os.ReadFile(filepath.Join(getTestDataPath(), "sample-root.pem"))
assertNil(t, err)

client.SetRootCertificateFromString(string(rootPemData))
Expand All @@ -218,9 +219,9 @@ func TestClientSetRootCertificateFromString(t *testing.T) {

func TestClientSetRootCertificateFromStringErrorTls(t *testing.T) {
client := NewWithClient(&http.Client{})
client.outputLogTo(ioutil.Discard)
client.outputLogTo(io.Discard)

rootPemData, err := ioutil.ReadFile(filepath.Join(getTestDataPath(), "sample-root.pem"))
rootPemData, err := os.ReadFile(filepath.Join(getTestDataPath(), "sample-root.pem"))
assertNil(t, err)
rt := &CustomRoundTripper{}
client.SetTransport(rt)
Expand Down Expand Up @@ -427,7 +428,7 @@ func TestClientPreRequestHook(t *testing.T) {
// Reading Request `N` no of times
for i := 0; i < 5; i++ {
b, _ := r.GetBody()
rb, _ := ioutil.ReadAll(b)
rb, _ := io.ReadAll(b)
c.log.Debugf("%s %v", string(rb), len(rb))
assertEqual(t, true, len(rb) >= 45)
}
Expand Down Expand Up @@ -486,7 +487,7 @@ func TestClientAllowsGetMethodPayloadDisabled(t *testing.T) {

func TestClientRoundTripper(t *testing.T) {
c := NewWithClient(&http.Client{})
c.outputLogTo(ioutil.Discard)
c.outputLogTo(io.Discard)

rt := &CustomRoundTripper{}
c.SetTransport(rt)
Expand Down Expand Up @@ -749,7 +750,7 @@ func TestClientOnResponseError(t *testing.T) {
assertEqual(t, 1, hook6)
}
}()
c := New().outputLogTo(ioutil.Discard).
c := New().outputLogTo(io.Discard).
SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}).
SetAuthToken("004DDB79-6801-4587-B976-F093E6AC44FF").
SetRetryCount(0).
Expand Down
4 changes: 1 addition & 3 deletions example_test.go
Expand Up @@ -7,7 +7,6 @@ package resty_test
import (
"crypto/tls"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
Expand Down Expand Up @@ -121,8 +120,7 @@ func Example_post() {
func Example_dropboxUpload() {
// For example: upload file to Dropbox
// POST of raw bytes for file upload.
file, _ := os.Open("/Users/jeeva/mydocument.pdf")
fileBytes, _ := ioutil.ReadAll(file)
fileBytes, _ := os.ReadFile("/Users/jeeva/mydocument.pdf")

// Create a resty client
client := resty.New()
Expand Down
7 changes: 3 additions & 4 deletions middleware.go
Expand Up @@ -9,7 +9,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
Expand Down Expand Up @@ -212,7 +211,7 @@ func createHTTPRequest(c *Client, r *Request) (err error) {
// assign get body func for the underlying raw request instance
r.RawRequest.GetBody = func() (io.ReadCloser, error) {
if bodyCopy != nil {
return ioutil.NopCloser(bytes.NewReader(bodyCopy.Bytes())), nil
return io.NopCloser(bytes.NewReader(bodyCopy.Bytes())), nil
}
return nil, nil
}
Expand Down Expand Up @@ -525,14 +524,14 @@ func getBodyCopy(r *Request) (*bytes.Buffer, error) {
// Maybe body is `io.Reader`.
// Note: Resty user have to watchout for large body size of `io.Reader`
if r.RawRequest.Body != nil {
b, err := ioutil.ReadAll(r.RawRequest.Body)
b, err := io.ReadAll(r.RawRequest.Body)
if err != nil {
return nil, err
}

// Restore the Body
closeq(r.RawRequest.Body)
r.RawRequest.Body = ioutil.NopCloser(bytes.NewBuffer(b))
r.RawRequest.Body = io.NopCloser(bytes.NewBuffer(b))

// Return the Body bytes
return bytes.NewBuffer(b), nil
Expand Down
22 changes: 9 additions & 13 deletions request_test.go
Expand Up @@ -10,7 +10,6 @@ import (
"encoding/xml"
"errors"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
Expand Down Expand Up @@ -84,7 +83,7 @@ func TestGetClientParamRequestParam(t *testing.T) {
c.SetQueryParam("client_param", "true").
SetQueryParams(map[string]string{"req_1": "jeeva", "req_3": "jeeva3"}).
SetDebug(true)
c.outputLogTo(ioutil.Discard)
c.outputLogTo(io.Discard)

resp, err := c.R().
SetQueryParams(map[string]string{"req_1": "req 1 value", "req_2": "req 2 value"}).
Expand Down Expand Up @@ -638,7 +637,7 @@ func TestFormData(t *testing.T) {
c.SetFormData(map[string]string{"zip_code": "00000", "city": "Los Angeles"}).
SetContentLength(true).
SetDebug(true)
c.outputLogTo(ioutil.Discard)
c.outputLogTo(io.Discard)

resp, err := c.R().
SetFormData(map[string]string{"first_name": "Jeevanandam", "last_name": "M", "zip_code": "00001"}).
Expand All @@ -660,7 +659,7 @@ func TestMultiValueFormData(t *testing.T) {

c := dc()
c.SetContentLength(true).SetDebug(true)
c.outputLogTo(ioutil.Discard)
c.outputLogTo(io.Discard)

resp, err := c.R().
SetQueryParamsFromValues(v).
Expand All @@ -680,7 +679,7 @@ func TestFormDataDisableWarn(t *testing.T) {
SetContentLength(true).
SetDebug(true).
SetDisableWarn(true)
c.outputLogTo(ioutil.Discard)
c.outputLogTo(io.Discard)

resp, err := c.R().
SetFormData(map[string]string{"first_name": "Jeevanandam", "last_name": "M", "zip_code": "00001"}).
Expand Down Expand Up @@ -781,8 +780,8 @@ func TestMultiPartIoReaderFiles(t *testing.T) {
defer cleanupFiles(".testdata/upload")

basePath := getTestDataPath()
profileImgBytes, _ := ioutil.ReadFile(filepath.Join(basePath, "test-img.png"))
notesBytes, _ := ioutil.ReadFile(filepath.Join(basePath, "text-file.txt"))
profileImgBytes, _ := os.ReadFile(filepath.Join(basePath, "test-img.png"))
notesBytes, _ := os.ReadFile(filepath.Join(basePath, "text-file.txt"))

// Just info values
file := File{
Expand Down Expand Up @@ -1033,7 +1032,7 @@ func TestPutJSONString(t *testing.T) {
})

client.SetDebug(true)
client.outputLogTo(ioutil.Discard)
client.outputLogTo(io.Discard)

resp, err := client.R().
SetHeaders(map[string]string{hdrContentTypeKey: "application/json; charset=utf-8", hdrAcceptKey: "application/json; charset=utf-8"}).
Expand Down Expand Up @@ -1202,9 +1201,7 @@ func TestRawFileUploadByBody(t *testing.T) {
ts := createFormPostServer(t)
defer ts.Close()

file, err := os.Open(filepath.Join(getTestDataPath(), "test-img.png"))
assertNil(t, err)
fileBytes, err := ioutil.ReadAll(file)
fileBytes, err := os.ReadFile(filepath.Join(getTestDataPath(), "test-img.png"))
assertNil(t, err)

resp, err := dclr().
Expand Down Expand Up @@ -1459,7 +1456,7 @@ func TestOutputFileWithBaseDirAndRelativePath(t *testing.T) {
SetRedirectPolicy(FlexibleRedirectPolicy(10)).
SetOutputDirectory(filepath.Join(getTestDataPath(), "dir-sample")).
SetDebug(true)
client.outputLogTo(ioutil.Discard)
client.outputLogTo(io.Discard)

resp, err := client.R().
SetOutput("go-resty/test-img-success.png").
Expand Down Expand Up @@ -1947,4 +1944,3 @@ func TestSetResultMustNotPanicOnNil(t *testing.T) {
}()
dc().R().SetResult(nil)
}

19 changes: 9 additions & 10 deletions resty_test.go
Expand Up @@ -11,7 +11,6 @@ import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
Expand Down Expand Up @@ -100,12 +99,12 @@ func createGetServer(t *testing.T) *httptest.Server {
time.Sleep(time.Second * 6)
_, _ = w.Write([]byte("TestClientTimeout page"))
case "/my-image.png":
fileBytes, _ := ioutil.ReadFile(filepath.Join(getTestDataPath(), "test-img.png"))
fileBytes, _ := os.ReadFile(filepath.Join(getTestDataPath(), "test-img.png"))
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Content-Length", strconv.Itoa(len(fileBytes)))
_, _ = w.Write(fileBytes)
case "/get-method-payload-test":
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("Error: could not read get body: %s", err.Error())
}
Expand Down Expand Up @@ -251,7 +250,7 @@ func createPostServer(t *testing.T) *httptest.Server {
// JSON
if IsJSONType(r.Header.Get(hdrContentTypeKey)) {
if r.URL.Query().Get("status") == "500" {
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("Error: could not read post body: %s", err.Error())
}
Expand Down Expand Up @@ -290,13 +289,13 @@ func createPostServer(t *testing.T) *httptest.Server {
w.Header().Set(hdrLocationKey, "/login")
w.WriteHeader(http.StatusTemporaryRedirect)
case "/redirect-with-body":
body, _ := ioutil.ReadAll(r.Body)
body, _ := io.ReadAll(r.Body)
query := url.Values{}
query.Add("body", string(body))
w.Header().Set(hdrLocationKey, "/redirected-with-body?"+query.Encode())
w.WriteHeader(http.StatusTemporaryRedirect)
case "/redirected-with-body":
body, _ := ioutil.ReadAll(r.Body)
body, _ := io.ReadAll(r.Body)
assertEqual(t, r.URL.Query().Get("body"), string(body))
w.WriteHeader(http.StatusOK)
}
Expand Down Expand Up @@ -582,7 +581,7 @@ func createGenServer(t *testing.T) *httptest.Server {
}

if r.Method == "REPORT" && r.URL.Path == "/report" {
body, _ := ioutil.ReadAll(r.Body)
body, _ := io.ReadAll(r.Body)
if len(body) == 0 {
w.WriteHeader(http.StatusOK)
}
Expand Down Expand Up @@ -628,14 +627,14 @@ func createTestServer(fn func(w http.ResponseWriter, r *http.Request)) *httptest

func dc() *Client {
c := New().
outputLogTo(ioutil.Discard)
outputLogTo(io.Discard)
return c
}

func dcl() *Client {
c := New().
SetDebug(true).
outputLogTo(ioutil.Discard)
outputLogTo(io.Discard)
return c
}

Expand All @@ -646,7 +645,7 @@ func dcr() *Request {
func dclr() *Request {
c := dc().
SetDebug(true).
outputLogTo(ioutil.Discard)
outputLogTo(io.Discard)
return c.R()
}

Expand Down

0 comments on commit 6400907

Please sign in to comment.