From 409ae21285078d375cc4433346f72c1c3b948b0d Mon Sep 17 00:00:00 2001 From: Yuan Date: Sat, 9 Mar 2024 18:41:57 +0800 Subject: [PATCH] Remove use if `ioutil` (deprecated) > "io/ioutil" has been deprecated since Go 1.16: As of Go 1.16, the same functionality is now provided by package io or package os, > and those implementations should be preferred in new code. See the specific function documentation for details. (SA1019) --- gorequest.go | 269 +++++++++++++++++++++++++-------------------------- 1 file changed, 131 insertions(+), 138 deletions(-) diff --git a/gorequest.go b/gorequest.go index 7e9594f..1b7d11e 100644 --- a/gorequest.go +++ b/gorequest.go @@ -8,7 +8,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "log" "mime/multipart" "net/http" @@ -87,7 +86,7 @@ type SuperAgent struct { Retryable superAgentRetryable DoNotClearSuperAgent bool isClone bool - context context.Context + context context.Context } var DisableTransportSwap = false @@ -232,7 +231,7 @@ func (s *SuperAgent) Clone() *SuperAgent { Retryable: copyRetryable(s.Retryable), DoNotClearSuperAgent: true, isClone: true, - context: s.context, + context: s.context, } return clone } @@ -368,10 +367,10 @@ func (s *SuperAgent) Options(targetUrl string) *SuperAgent { // this will overwrite the existed values of Header through AppendHeader(). // Example. To set `Accept` as `application/json` // -// gorequest.New(). -// Post("/gamelist"). -// Set("Accept", "application/json"). -// End() +// gorequest.New(). +// Post("/gamelist"). +// Set("Accept", "application/json"). +// End() func (s *SuperAgent) Set(param string, value string) *SuperAgent { s.Header.Set(param, value) return s @@ -380,11 +379,11 @@ func (s *SuperAgent) Set(param string, value string) *SuperAgent { // AppendHeader is used for setting header fileds with multiple values, // Example. To set `Accept` as `application/json, text/plain` // -// gorequest.New(). -// Post("/gamelist"). -// AppendHeader("Accept", "application/json"). -// AppendHeader("Accept", "text/plain"). -// End() +// gorequest.New(). +// Post("/gamelist"). +// AppendHeader("Accept", "application/json"). +// AppendHeader("Accept", "text/plain"). +// End() func (s *SuperAgent) AppendHeader(param string, value string) *SuperAgent { s.Header.Add(param, value) return s @@ -395,10 +394,11 @@ func (s *SuperAgent) AppendHeader(param string, value string) *SuperAgent { // 3 max attempt. // And StatusBadRequest and StatusInternalServerError as RetryableStatus -// gorequest.New(). -// Post("/gamelist"). -// Retry(3, 5 * time.Second, http.StatusBadRequest, http.StatusInternalServerError). -// End() +// gorequest.New(). +// +// Post("/gamelist"). +// Retry(3, 5 * time.Second, http.StatusBadRequest, http.StatusInternalServerError). +// End() func (s *SuperAgent) Retry(retryerCount int, retryerTime time.Duration, statusCode ...int) *SuperAgent { for _, code := range statusCode { statusText := http.StatusText(code) @@ -426,10 +426,10 @@ func (s *SuperAgent) Retry(retryerCount int, retryerTime time.Duration, statusCo // SetBasicAuth sets the basic authentication header // Example. To set the header for username "myuser" and password "mypass" // -// gorequest.New() -// Post("/gamelist"). -// SetBasicAuth("myuser", "mypass"). -// End() +// gorequest.New() +// Post("/gamelist"). +// SetBasicAuth("myuser", "mypass"). +// End() func (s *SuperAgent) SetBasicAuth(username string, password string) *SuperAgent { s.BasicAuth = struct{ Username, Password string }{username, password} return s @@ -461,22 +461,21 @@ var Types = map[string]string{ // Type is a convenience function to specify the data type to send. // For example, to send data as `application/x-www-form-urlencoded` : // -// gorequest.New(). -// Post("/recipe"). -// Type("form"). -// Send(`{ "name": "egg benedict", "category": "brunch" }`). -// End() +// gorequest.New(). +// Post("/recipe"). +// Type("form"). +// Send(`{ "name": "egg benedict", "category": "brunch" }`). +// End() // // This will POST the body "name=egg benedict&category=brunch" to url /recipe // // GoRequest supports // -// "text/html" uses "html" -// "application/json" uses "json" -// "application/xml" uses "xml" -// "text/plain" uses "text" -// "application/x-www-form-urlencoded" uses "urlencoded", "form" or "form-data" -// +// "text/html" uses "html" +// "application/json" uses "json" +// "application/xml" uses "xml" +// "text/plain" uses "text" +// "application/x-www-form-urlencoded" uses "urlencoded", "form" or "form-data" func (s *SuperAgent) Type(typeStr string) *SuperAgent { if _, ok := Types[typeStr]; ok { s.ForceType = typeStr @@ -489,36 +488,35 @@ func (s *SuperAgent) Type(typeStr string) *SuperAgent { // Query function accepts either json string or strings which will form a query-string in url of GET method or body of POST method. // For example, making "/search?query=bicycle&size=50x50&weight=20kg" using GET method: // -// gorequest.New(). -// Get("/search"). -// Query(`{ query: 'bicycle' }`). -// Query(`{ size: '50x50' }`). -// Query(`{ weight: '20kg' }`). -// End() +// gorequest.New(). +// Get("/search"). +// Query(`{ query: 'bicycle' }`). +// Query(`{ size: '50x50' }`). +// Query(`{ weight: '20kg' }`). +// End() // // Or you can put multiple json values: // -// gorequest.New(). -// Get("/search"). -// Query(`{ query: 'bicycle', size: '50x50', weight: '20kg' }`). -// End() +// gorequest.New(). +// Get("/search"). +// Query(`{ query: 'bicycle', size: '50x50', weight: '20kg' }`). +// End() // // Strings are also acceptable: // -// gorequest.New(). -// Get("/search"). -// Query("query=bicycle&size=50x50"). -// Query("weight=20kg"). -// End() +// gorequest.New(). +// Get("/search"). +// Query("query=bicycle&size=50x50"). +// Query("weight=20kg"). +// End() // // Or even Mixed! :) // -// gorequest.New(). -// Get("/search"). -// Query("query=bicycle"). -// Query(`{ size: '50x50', weight:'20kg' }`). -// End() -// +// gorequest.New(). +// Get("/search"). +// Query("query=bicycle"). +// Query(`{ size: '50x50', weight:'20kg' }`). +// End() func (s *SuperAgent) Query(content interface{}) *SuperAgent { switch v := reflect.ValueOf(content); v.Kind() { case reflect.String: @@ -600,10 +598,9 @@ func (s *SuperAgent) Param(key string, value string) *SuperAgent { // Set TLSClientConfig for underling Transport. // One example is you can use it to disable security check (https): // -// gorequest.New().TLSClientConfig(&tls.Config{ InsecureSkipVerify: true}). -// Get("https://disable-security-check.com"). -// End() -// +// gorequest.New().TLSClientConfig(&tls.Config{ InsecureSkipVerify: true}). +// Get("https://disable-security-check.com"). +// End() func (s *SuperAgent) TLSClientConfig(config *tls.Config) *SuperAgent { s.safeModifyTransport() s.Transport.TLSClientConfig = config @@ -616,16 +613,15 @@ func (s *SuperAgent) TLSClientConfig(config *tls.Config) *SuperAgent { // You will not be able to send different request with different proxy unless you change your `http_proxy` environment again. // Another example is using Golang proxy setting. This is normal prefer way to do but too verbase compared to GoRequest's Proxy: // -// gorequest.New().Proxy("http://myproxy:9999"). -// Post("http://www.google.com"). -// End() +// gorequest.New().Proxy("http://myproxy:9999"). +// Post("http://www.google.com"). +// End() // // To set no_proxy, just put empty string to Proxy func: // -// gorequest.New().Proxy(""). -// Post("http://www.google.com"). -// End() -// +// gorequest.New().Proxy(""). +// Post("http://www.google.com"). +// End() func (s *SuperAgent) Proxy(proxyUrl string) *SuperAgent { parsedProxyUrl, err := url.Parse(proxyUrl) if err != nil { @@ -661,48 +657,47 @@ func (s *SuperAgent) RedirectPolicy(policy func(req Request, via []Request) erro // Send function accepts either json string or query strings which is usually used to assign data to POST or PUT method. // Without specifying any type, if you give Send with json data, you are doing requesting in json format: // -// gorequest.New(). -// Post("/search"). -// Send(`{ query: 'sushi' }`). -// End() +// gorequest.New(). +// Post("/search"). +// Send(`{ query: 'sushi' }`). +// End() // // While if you use at least one of querystring, GoRequest understands and automatically set the Content-Type to `application/x-www-form-urlencoded` // -// gorequest.New(). -// Post("/search"). -// Send("query=tonkatsu"). -// End() +// gorequest.New(). +// Post("/search"). +// Send("query=tonkatsu"). +// End() // // So, if you want to strictly send json format, you need to use Type func to set it as `json` (Please see more details in Type function). // You can also do multiple chain of Send: // -// gorequest.New(). -// Post("/search"). -// Send("query=bicycle&size=50x50"). -// Send(`{ wheel: '4'}`). -// End() +// gorequest.New(). +// Post("/search"). +// Send("query=bicycle&size=50x50"). +// Send(`{ wheel: '4'}`). +// End() // // From v0.2.0, Send function provide another convenience way to work with Struct type. You can mix and match it with json and query string: // -// type BrowserVersionSupport struct { -// Chrome string -// Firefox string -// } -// ver := BrowserVersionSupport{ Chrome: "37.0.2041.6", Firefox: "30.0" } -// gorequest.New(). -// Post("/update_version"). -// Send(ver). -// Send(`{"Safari":"5.1.10"}`). -// End() +// type BrowserVersionSupport struct { +// Chrome string +// Firefox string +// } +// ver := BrowserVersionSupport{ Chrome: "37.0.2041.6", Firefox: "30.0" } +// gorequest.New(). +// Post("/update_version"). +// Send(ver). +// Send(`{"Safari":"5.1.10"}`). +// End() // // If you have set Type to text or Content-Type to text/plain, content will be sent as raw string in body instead of form // -// gorequest.New(). -// Post("/greet"). -// Type("text"). -// Send("hello world"). -// End() -// +// gorequest.New(). +// Post("/greet"). +// Type("text"). +// Send("hello world"). +// End() func (s *SuperAgent) Send(content interface{}) *SuperAgent { // TODO: add normal text mode or other mode to Send func switch v := reflect.ValueOf(content); v.Kind() { @@ -842,51 +837,50 @@ type File struct { // SendFile function works only with type "multipart". The function accepts one mandatory and up to two optional arguments. The mandatory (first) argument is the file. // The function accepts a path to a file as string: // -// gorequest.New(). -// Post("http://example.com"). -// Type("multipart"). -// SendFile("./example_file.ext"). -// End() +// gorequest.New(). +// Post("http://example.com"). +// Type("multipart"). +// SendFile("./example_file.ext"). +// End() // -// File can also be a []byte slice of a already file read by eg. ioutil.ReadFile: +// File can also be a []byte slice of a already file read by eg. os.ReadFile: // -// b, _ := ioutil.ReadFile("./example_file.ext") -// gorequest.New(). -// Post("http://example.com"). -// Type("multipart"). -// SendFile(b). -// End() +// b, _ := os.ReadFile("./example_file.ext") +// gorequest.New(). +// Post("http://example.com"). +// Type("multipart"). +// SendFile(b). +// End() // // Furthermore file can also be a os.File: // -// f, _ := os.Open("./example_file.ext") -// gorequest.New(). -// Post("http://example.com"). -// Type("multipart"). -// SendFile(f). -// End() +// f, _ := os.Open("./example_file.ext") +// gorequest.New(). +// Post("http://example.com"). +// Type("multipart"). +// SendFile(f). +// End() // // The first optional argument (second argument overall) is the filename, which will be automatically determined when file is a string (path) or a os.File. // When file is a []byte slice, filename defaults to "filename". In all cases the automatically determined filename can be overwritten: // -// b, _ := ioutil.ReadFile("./example_file.ext") -// gorequest.New(). -// Post("http://example.com"). -// Type("multipart"). -// SendFile(b, "my_custom_filename"). -// End() +// b, _ := os.ReadFile("./example_file.ext") +// gorequest.New(). +// Post("http://example.com"). +// Type("multipart"). +// SendFile(b, "my_custom_filename"). +// End() // // The second optional argument (third argument overall) is the fieldname in the multipart/form-data request. It defaults to fileNUMBER (eg. file1), where number is ascending and starts counting at 1. // So if you send multiple files, the fieldnames will be file1, file2, ... unless it is overwritten. If fieldname is set to "file" it will be automatically set to fileNUMBER, where number is the greatest exsiting number+1 unless // a third argument skipFileNumbering is provided and true. // -// b, _ := ioutil.ReadFile("./example_file.ext") -// gorequest.New(). -// Post("http://example.com"). -// Type("multipart"). -// SendFile(b, "", "my_custom_fieldname"). // filename left blank, will become "example_file.ext" -// End() -// +// b, _ := os.ReadFile("./example_file.ext") +// gorequest.New(). +// Post("http://example.com"). +// Type("multipart"). +// SendFile(b, "", "my_custom_fieldname"). // filename left blank, will become "example_file.ext" +// End() func (s *SuperAgent) SendFile(file interface{}, args ...interface{}) *SuperAgent { filename := "" @@ -928,7 +922,7 @@ func (s *SuperAgent) SendFile(file interface{}, args ...interface{}) *SuperAgent if filename == "" { filename = filepath.Base(pathToFile) } - data, err := ioutil.ReadFile(v.String()) + data, err := os.ReadFile(v.String()) if err != nil { s.Errors = append(s.Errors, err) return s @@ -969,7 +963,7 @@ func (s *SuperAgent) SendFile(file interface{}, args ...interface{}) *SuperAgent if filename == "" { filename = filepath.Base(osfile.Name()) } - data, err := ioutil.ReadFile(osfile.Name()) + data, err := os.ReadFile(osfile.Name()) if err != nil { s.Errors = append(s.Errors, err) return s @@ -1064,22 +1058,21 @@ func changeMapToURLValues(data map[string]interface{}) url.Values { // // For example: // -// resp, body, errs := gorequest.New().Get("http://www.google.com").End() -// if errs != nil { -// fmt.Println(errs) -// } -// fmt.Println(resp, body) +// resp, body, errs := gorequest.New().Get("http://www.google.com").End() +// if errs != nil { +// fmt.Println(errs) +// } +// fmt.Println(resp, body) // // Moreover, End function also supports callback which you can put as a parameter. // This extends the flexibility and makes GoRequest fun and clean! You can use GoRequest in whatever style you love! // // For example: // -// func printBody(resp gorequest.Response, body string, errs []error){ -// fmt.Println(resp.Status) -// } -// gorequest.New().Get("http://www..google.com").End(printBody) -// +// func printBody(resp gorequest.Response, body string, errs []error){ +// fmt.Println(resp.Status) +// } +// gorequest.New().Get("http://www..google.com").End(printBody) func (s *SuperAgent) End(callback ...func(response Response, body string, errs []error)) (Response, string, []error) { var bytesCallback []func(response Response, body []byte, errs []error) if len(callback) > 0 { @@ -1140,7 +1133,7 @@ func contains(respStatus int, statuses []int) bool { return false } -func (s *SuperAgent) Context(ctx context.Context) *SuperAgent{ +func (s *SuperAgent) Context(ctx context.Context) *SuperAgent { if ctx == nil { panic("context can't be nil") } @@ -1248,9 +1241,9 @@ func (s *SuperAgent) getResponseBytes() (Response, []byte, []error) { } } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) // Reset resp.Body so it can be use again - resp.Body = ioutil.NopCloser(bytes.NewBuffer(body)) + resp.Body = io.NopCloser(bytes.NewBuffer(body)) if err != nil { return nil, nil, []error{err} }