Handle ioutil deprecations (#53526)

* replace ioutil.ReadFile -> os.ReadFile

* replace ioutil.ReadAll -> io.ReadAll

* replace ioutil.TempFile -> os.CreateTemp

* replace ioutil.NopCloser -> io.NopCloser

* replace ioutil.WriteFile -> os.WriteFile

* replace ioutil.TempDir -> os.MkdirTemp

* replace ioutil.Discard -> io.Discard
This commit is contained in:
Jo 2022-08-10 13:37:51 +00:00 committed by GitHub
parent 4926767737
commit 062d255124
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
140 changed files with 462 additions and 492 deletions

View File

@ -3,14 +3,13 @@ package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"strings"
)
func hello(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
if err != nil {
return
}

View File

@ -11,9 +11,9 @@ import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
@ -188,7 +188,7 @@ func newNotFound(cfg *setting.Cfg) *Avatar {
// It's safe to ignore gosec warning G304 since the variable part of the file path comes from a configuration
// variable.
// nolint:gosec
if data, err := ioutil.ReadFile(path); err != nil {
if data, err := os.ReadFile(path); err != nil {
alog.Error("Failed to read user_profile.png", "path", path)
} else {
avatar.data = bytes.NewBuffer(data)

View File

@ -5,8 +5,8 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"testing"
"github.com/stretchr/testify/assert"
@ -77,7 +77,7 @@ func TestGetHomeDashboard(t *testing.T) {
dash.Meta.IsHome = true
dash.Meta.FolderTitle = "General"
homeDashJSON, err := ioutil.ReadFile(tc.expectedDashboardPath)
homeDashJSON, err := os.ReadFile(tc.expectedDashboardPath)
require.NoError(t, err, "must be able to read expected dashboard file")
hs.Cfg.DefaultHomeDashboardPath = tc.defaultSetting
bytes, err := simplejson.NewJson(homeDashJSON)

View File

@ -2,7 +2,6 @@ package api
import (
"errors"
"io/ioutil"
"net/url"
"os"
"strings"
@ -68,7 +67,7 @@ func logSentryEventScenario(t *testing.T, desc string, event frontendlogging.Fro
return nil, errors.New("epic hard drive failure")
}
if strings.HasSuffix(path, "foo.js.map") {
f, err := ioutil.ReadFile("./frontendlogging/test-data/foo.js.map")
f, err := os.ReadFile("./frontendlogging/test-data/foo.js.map")
require.NoError(t, err)
return f, nil
}
@ -140,7 +139,7 @@ func logGrafanaJavascriptAgentEventScenario(t *testing.T, desc string, event fro
return nil, errors.New("epic hard drive failure")
}
if strings.HasSuffix(path, "foo.js.map") {
f, err := ioutil.ReadFile("./frontendlogging/test-data/foo.js.map")
f, err := os.ReadFile("./frontendlogging/test-data/foo.js.map")
require.NoError(t, err)
return f, nil
}

View File

@ -1,7 +1,7 @@
package frontendlogging
import (
"io/ioutil"
"io"
"net/http"
"net/url"
"os"
@ -39,7 +39,7 @@ func ReadSourceMapFromFS(dir string, path string) ([]byte, error) {
logger.Error("Failed to close source map file", "err", err)
}
}()
return ioutil.ReadAll(file)
return io.ReadAll(file)
}
type SourceMapStore struct {

View File

@ -7,7 +7,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
@ -61,7 +60,7 @@ func fakeViewIndex(t *testing.T) {
}
func getBody(resp *httptest.ResponseRecorder) (string, error) {
responseData, err := ioutil.ReadAll(resp.Body)
responseData, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}

View File

@ -4,7 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"testing"
@ -89,7 +89,7 @@ func TestGetPluginDashboards(t *testing.T) {
resp, err := sendGetPluginDashboardsRequestForSignedInUser(t, s, existingPluginID, user)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
bytes, err := ioutil.ReadAll(resp.Body)
bytes, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
var listResp []*plugindashboards.PluginDashboard

View File

@ -2,7 +2,7 @@ package api
import (
"context"
"io/ioutil"
"io"
"net/http"
"testing"
@ -39,7 +39,7 @@ func TestPluginMetricsEndpoint(t *testing.T) {
require.NoError(t, err)
require.NotNil(t, resp)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, "http_errors=2", string(body))
require.NoError(t, resp.Body.Close())
@ -53,7 +53,7 @@ func TestPluginMetricsEndpoint(t *testing.T) {
require.NoError(t, err)
require.NotNil(t, resp)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Empty(t, string(body))
require.NoError(t, resp.Body.Close())
@ -106,7 +106,7 @@ func TestPluginMetricsEndpoint(t *testing.T) {
require.NoError(t, err)
require.NotNil(t, resp)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, "http_errors=2", string(body))
require.NoError(t, resp.Body.Close())

View File

@ -6,7 +6,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"sync"
@ -121,7 +120,7 @@ func (hs *HTTPServer) makePluginResourceRequest(w http.ResponseWriter, req *http
proxyutil.ClearCookieHeader(req, keepCookieModel.KeepCookies)
proxyutil.PrepareProxyRequest(req)
body, err := ioutil.ReadAll(req.Body)
body, err := io.ReadAll(req.Body)
if err != nil {
return fmt.Errorf("failed to read request body: %w", err)
}

View File

@ -4,7 +4,7 @@ import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/url"
"strconv"
@ -106,7 +106,7 @@ func (proxy *DataSourceProxy) HandleRequest() {
modifyResponse := func(resp *http.Response) error {
if resp.StatusCode == 401 {
// The data source rejected the request as unauthorized, convert to 400 (bad request)
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read data source response body: %w", err)
}
@ -118,7 +118,7 @@ func (proxy *DataSourceProxy) HandleRequest() {
*resp = http.Response{
StatusCode: 400,
Status: "Bad Request",
Body: ioutil.NopCloser(strings.NewReader(msg)),
Body: io.NopCloser(strings.NewReader(msg)),
ContentLength: int64(len(msg)),
Header: http.Header{},
}
@ -324,9 +324,9 @@ func (proxy *DataSourceProxy) logRequest() {
var body string
if proxy.ctx.Req.Body != nil {
buffer, err := ioutil.ReadAll(proxy.ctx.Req.Body)
buffer, err := io.ReadAll(proxy.ctx.Req.Body)
if err == nil {
proxy.ctx.Req.Body = ioutil.NopCloser(bytes.NewBuffer(buffer))
proxy.ctx.Req.Body = io.NopCloser(bytes.NewBuffer(buffer))
body = string(buffer)
}
}

View File

@ -5,10 +5,11 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"
"time"
@ -176,7 +177,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
proxy.matchedRoute = routes[5]
ApplyRoute(proxy.ctx.Req.Context(), req, proxy.proxyPath, proxy.matchedRoute, dsInfo, cfg)
content, err := ioutil.ReadAll(req.Body)
content, err := io.ReadAll(req.Body)
require.NoError(t, err)
require.Equal(t, `{ "url": "https://dynamic.grafana.com", "secret": "123" }`, string(content))
})
@ -275,7 +276,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
var authorizationHeaderCall2 string
t.Run("first call should add authorization header with access token", func(t *testing.T) {
json, err := ioutil.ReadFile("./test-data/access-token-1.json")
json, err := os.ReadFile("./test-data/access-token-1.json")
require.NoError(t, err)
originalClient := client
@ -303,7 +304,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
assert.True(t, strings.HasPrefix(authorizationHeaderCall1, "Bearer eyJ0e"))
t.Run("second call to another route should add a different access token", func(t *testing.T) {
json2, err := ioutil.ReadFile("./test-data/access-token-2.json")
json2, err := os.ReadFile("./test-data/access-token-2.json")
require.NoError(t, err)
req, err := http.NewRequest("GET", "http://localhost/asd", nil)
@ -887,7 +888,7 @@ func (c *httpClientStub) Do(req *http.Request) (*http.Response, error) {
body, err := bodyJSON.MarshalJSON()
require.NoError(c.t, err)
resp := &http.Response{
Body: ioutil.NopCloser(bytes.NewReader(body)),
Body: io.NopCloser(bytes.NewReader(body)),
}
return resp, nil

View File

@ -3,7 +3,7 @@ package pluginproxy
import (
"bytes"
"encoding/json"
"io/ioutil"
"io"
"net/http"
"net/http/httputil"
"net/url"
@ -107,9 +107,9 @@ func logAppPluginProxyRequest(appID string, cfg *setting.Cfg, c *models.ReqConte
var body string
if c.Req.Body != nil {
buffer, err := ioutil.ReadAll(c.Req.Body)
buffer, err := io.ReadAll(c.Req.Body)
if err == nil {
c.Req.Body = ioutil.NopCloser(bytes.NewBuffer(buffer))
c.Req.Body = io.NopCloser(bytes.NewBuffer(buffer))
body = string(buffer)
}
}

View File

@ -2,7 +2,7 @@ package pluginproxy
import (
"context"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"testing"
@ -241,7 +241,7 @@ func TestPluginProxy(t *testing.T) {
route,
store,
)
content, err := ioutil.ReadAll(req.Body)
content, err := io.ReadAll(req.Body)
require.NoError(t, err)
require.Equal(t, `{ "url": "https://dynamic.grafana.com", "secret": "123" }`, string(content))
})

View File

@ -3,7 +3,7 @@ package pluginproxy
import (
"bytes"
"fmt"
"io/ioutil"
"io"
"net/http"
"strings"
"text/template"
@ -78,7 +78,7 @@ func setBodyContent(req *http.Request, route *plugins.Route, data templateData)
return err
}
req.Body = ioutil.NopCloser(strings.NewReader(interpolatedBody))
req.Body = io.NopCloser(strings.NewReader(interpolatedBody))
req.ContentLength = int64(len(interpolatedBody))
}

View File

@ -5,7 +5,6 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
@ -466,7 +465,7 @@ func (hs *HTTPServer) pluginMarkdown(ctx context.Context, pluginId string, name
// nolint:gosec
// We can ignore the gosec G304 warning since we have cleaned the requested file path and subsequently
// use this with a prefix of the plugin's directory, which is set during plugin loading
data, err := ioutil.ReadFile(path)
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}

View File

@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
@ -101,9 +100,9 @@ func Test_PluginsInstallAndUninstall(t *testing.T) {
func Test_GetPluginAssets(t *testing.T) {
pluginID := "test-plugin"
pluginDir := "."
tmpFile, err := ioutil.TempFile(pluginDir, "")
tmpFile, err := os.CreateTemp(pluginDir, "")
require.NoError(t, err)
tmpFileInParentDir, err := ioutil.TempFile("..", "")
tmpFileInParentDir, err := os.CreateTemp("..", "")
require.NoError(t, err)
t.Cleanup(func() {
err := os.RemoveAll(tmpFile.Name())

View File

@ -2,7 +2,7 @@ package api
import (
"encoding/json"
"io/ioutil"
"io"
"net/http"
"strings"
"testing"
@ -60,7 +60,7 @@ func TestAPIEndpoint_GetCurrentOrgPreferences_LegacyAccessControl(t *testing.T)
response := callAPI(sc.server, http.MethodGet, getOrgPreferencesURL, nil, t)
assert.Equal(t, http.StatusOK, response.Code)
var resp map[string]interface{}
b, err := ioutil.ReadAll(response.Body)
b, err := io.ReadAll(response.Body)
assert.NoError(t, err)
assert.NoError(t, json.Unmarshal(b, &resp))
assert.Equal(t, "home", resp["homeDashboardUID"])

View File

@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
@ -103,7 +102,7 @@ func shortenBuildID(buildID string) string {
func GetGrafanaVersion(buildID, grafanaDir string) (string, error) {
pkgJSONPath := filepath.Join(grafanaDir, "package.json")
//nolint:gosec
pkgJSONB, err := ioutil.ReadFile(pkgJSONPath)
pkgJSONB, err := os.ReadFile(pkgJSONPath)
if err != nil {
return "", fmt.Errorf("failed to read %q: %w", pkgJSONPath, err)
}

View File

@ -4,7 +4,6 @@ import (
"crypto/md5"
"fmt"
"io"
"io/ioutil"
"log"
"os"
)
@ -28,7 +27,7 @@ func MD5File(fpath string) error {
}
// nolint:gosec
if err := ioutil.WriteFile(fpath+".md5", []byte(fmt.Sprintf("%x\n", h.Sum(nil))), 0664); err != nil {
if err := os.WriteFile(fpath+".md5", []byte(fmt.Sprintf("%x\n", h.Sum(nil))), 0664); err != nil {
return err
}

View File

@ -5,7 +5,6 @@ import (
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
@ -20,7 +19,7 @@ func verifyArchive(archive string) error {
log.Printf("Verifying checksum of %q", archive)
//nolint:gosec
shaB, err := ioutil.ReadFile(archive + ".sha256")
shaB, err := os.ReadFile(archive + ".sha256")
if err != nil {
return err
}

View File

@ -7,7 +7,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
@ -54,7 +53,7 @@ func Download(ctx context.Context, grafanaDir string, p syncutil.WorkerPool) err
var m pluginsManifest
manifestPath := filepath.Join(grafanaDir, "plugins-bundled", "external.json")
//nolint:gosec
manifestB, err := ioutil.ReadFile(manifestPath)
manifestB, err := os.ReadFile(manifestPath)
if err != nil {
return fmt.Errorf("failed to open plugins manifest %q: %w", manifestPath, err)
}

View File

@ -7,7 +7,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
@ -105,7 +104,7 @@ func BuildManifest(ctx context.Context, dpath string, signingAdmin bool) error {
}
}()
if resp.StatusCode != 200 {
msg, err := ioutil.ReadAll(resp.Body)
msg, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("Failed to read response body: %s", err)
msg = []byte("")

View File

@ -7,7 +7,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
@ -142,7 +141,7 @@ func sendRequestGetBytes(client http.Client, repoUrl string, subPaths ...string)
logger.Warn("Failed to close stream", "err", err)
}
}()
return ioutil.ReadAll(bodyReader)
return io.ReadAll(bodyReader)
}
func sendRequest(client http.Client, repoUrl string, subPaths ...string) (io.ReadCloser, error) {
@ -191,7 +190,7 @@ func handleResponse(res *http.Response) (io.ReadCloser, error) {
}
if res.StatusCode/100 == 4 {
body, err := ioutil.ReadAll(res.Body)
body, err := io.ReadAll(res.Body)
defer func() {
if err := res.Body.Close(); err != nil {
logger.Warn("Failed to close response body", "err", err)

View File

@ -4,7 +4,6 @@ import (
"bytes"
"errors"
"io"
"io/ioutil"
"net/http"
"testing"
@ -19,7 +18,7 @@ func TestHandleResponse(t *testing.T) {
resp := makeResponse(t, 200, "test")
bodyReader, err := handleResponse(resp)
require.NoError(t, err)
body, err := ioutil.ReadAll(bodyReader)
body, err := io.ReadAll(bodyReader)
require.NoError(t, err)
assert.Equal(t, "test", string(body))
})
@ -81,7 +80,7 @@ func makeResponse(t *testing.T, status int, body string) *http.Response {
func makeBody(t *testing.T, body string) io.ReadCloser {
t.Helper()
reader := ioutil.NopCloser(bytes.NewReader([]byte(body)))
reader := io.NopCloser(bytes.NewReader([]byte(body)))
t.Cleanup(func() {
err := reader.Close()
assert.NoError(t, err)

View File

@ -25,5 +25,5 @@ func (i IoUtilImp) ReadFile(filename string) ([]byte, error) {
// from command line flag "pluginsDir". If the user shouldn't be reading from this directory, they shouldn't have
// the permission in the file system.
// nolint:gosec
return ioutil.ReadFile(filename)
return os.ReadFile(filename)
}

View File

@ -8,7 +8,7 @@ import (
"go/format"
"go/parser"
"go/token"
"io/ioutil"
"io"
"os"
"path/filepath"
"regexp"
@ -79,7 +79,7 @@ func ExtractLineage(path string, lib thema.Library) (*ExtractedLineage, error) {
return nil, fmt.Errorf("could not open lineage file at %s: %w", path, err)
}
byt, err := ioutil.ReadAll(f)
byt, err := io.ReadAll(f)
if err != nil {
return nil, err
}

View File

@ -9,7 +9,6 @@ import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"mime"
"net/http"
"net/url"
@ -77,7 +76,7 @@ func (az *AzureBlobUploader) Upload(ctx context.Context, imageDiskPath string) (
}()
if resp.StatusCode > 400 && resp.StatusCode < 600 {
body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1<<20))
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
return "", err
}
@ -256,14 +255,15 @@ func tryget(headers map[string][]string, key string) string {
/*
Based on Azure docs:
Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element
1) Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header.
2) Convert each HTTP header name to lowercase.
3) Sort the headers lexicographically by header name, in ascending order. Note that each header may appear only once in the string.
4) Unfold the string by replacing any breaking white space with a single space.
5) Trim any white space around the colon in the header.
6) Finally, append a new line character to each canonicalized header in the resulting list. Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string.
Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element
1) Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header.
2) Convert each HTTP header name to lowercase.
3) Sort the headers lexicographically by header name, in ascending order. Note that each header may appear only once in the string.
4) Unfold the string by replacing any breaking white space with a single space.
5) Trim any white space around the colon in the header.
6) Finally, append a new line character to each canonicalized header in the resulting list. Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string.
*/
func (a *Auth) canonicalizedHeaders(req *http.Request) string {
var buffer bytes.Buffer
@ -288,25 +288,26 @@ func (a *Auth) canonicalizedHeaders(req *http.Request) string {
/*
Based on Azure docs
Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element
1) Beginning with an empty string (""), append a forward slash (/), followed by the name of the account that owns the resource being accessed.
2) Append the resource's encoded URI path, without any query parameters.
3) Retrieve all query parameters on the resource URI, including the comp parameter if it exists.
4) Convert all parameter names to lowercase.
5) Sort the query parameters lexicographically by parameter name, in ascending order.
6) URL-decode each query parameter name and value.
7) Append each query parameter name and value to the string in the following format, making sure to include the colon (:) between the name and the value:
parameter-name:parameter-value
Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element
8) If a query parameter has more than one value, sort all values lexicographically, then include them in a comma-separated list:
parameter-name:parameter-value-1,parameter-value-2,parameter-value-n
1. Beginning with an empty string (""), append a forward slash (/), followed by the name of the account that owns the resource being accessed.
2. Append the resource's encoded URI path, without any query parameters.
3. Retrieve all query parameters on the resource URI, including the comp parameter if it exists.
4. Convert all parameter names to lowercase.
5. Sort the query parameters lexicographically by parameter name, in ascending order.
6. URL-decode each query parameter name and value.
7. Append each query parameter name and value to the string in the following format, making sure to include the colon (:) between the name and the value:
parameter-name:parameter-value
8. If a query parameter has more than one value, sort all values lexicographically, then include them in a comma-separated list:
parameter-name:parameter-value-1,parameter-value-2,parameter-value-n
9) Append a new line character (\n) after each name-value pair.
Rules:
1) Avoid using the new line character (\n) in values for query parameters. If it must be used, ensure that it does not affect the format of the canonicalized resource string.
2) Avoid using commas in query parameter values.
1. Avoid using the new line character (\n) in values for query parameters. If it must be used, ensure that it does not affect the format of the canonicalized resource string.
2. Avoid using commas in query parameter values.
*/
func (a *Auth) canonicalizedResource(req *http.Request) string {
var buffer bytes.Buffer

View File

@ -5,7 +5,6 @@ import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
@ -75,7 +74,7 @@ func (u *Uploader) Upload(ctx context.Context, imageDiskPath string) (string, er
var keyData []byte
if u.KeyFile != "" {
u.log.Debug("Opening key file ", u.KeyFile)
keyData, err = ioutil.ReadFile(u.KeyFile)
keyData, err = os.ReadFile(u.KeyFile)
if err != nil {
return "", err
}

View File

@ -4,7 +4,7 @@ import (
"bytes"
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
"time"
@ -115,7 +115,7 @@ func TestUploadToGCS_DefaultCredentials(t *testing.T) {
content := []byte("test\n")
tmpDir := t.TempDir()
fpath := filepath.Join(tmpDir, "test.png")
err := ioutil.WriteFile(fpath, content, 0600)
err := os.WriteFile(fpath, content, 0600)
require.NoError(t, err)
t.Run("Without signed URL", func(t *testing.T) {

View File

@ -4,10 +4,11 @@ import (
"bytes"
"context"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"net/url"
"os"
"path"
"strings"
"time"
@ -58,7 +59,7 @@ func (u *WebdavUploader) Upload(ctx context.Context, imgToUpload string) (string
// We can ignore the gosec G304 warning on this one because `imgToUpload` comes
// from alert notifiers and is only used to upload images generated by alerting.
// nolint:gosec
imgData, err := ioutil.ReadFile(imgToUpload)
imgData, err := os.ReadFile(imgToUpload)
if err != nil {
return "", err
}
@ -85,7 +86,7 @@ func (u *WebdavUploader) Upload(ctx context.Context, imgToUpload string) (string
}()
if res.StatusCode != http.StatusCreated {
body, err := ioutil.ReadAll(res.Body)
body, err := io.ReadAll(res.Body)
if err != nil {
return "", fmt.Errorf("failed to read response body: %w", err)
}

View File

@ -4,7 +4,6 @@ import (
"context"
"encoding/base64"
"fmt"
"io/ioutil"
"os"
"path"
"testing"
@ -87,7 +86,7 @@ func runTests(createCases func() []fsTestCase, t *testing.T) {
setupLocalFs := func() {
commonSetup()
tmpDir, err := ioutil.TempDir("", "")
tmpDir, err := os.MkdirTemp("", "")
tempDir = tmpDir
if err != nil {
t.Fatal(err)
@ -102,7 +101,7 @@ func runTests(createCases func() []fsTestCase, t *testing.T) {
setupLocalFsNestedPath := func() {
commonSetup()
tmpDir, err := ioutil.TempDir("", "")
tmpDir, err := os.MkdirTemp("", "")
if err != nil {
t.Fatal(err)
}

View File

@ -1,7 +1,6 @@
package fs
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
@ -12,16 +11,16 @@ import (
)
func TestCopyFile(t *testing.T) {
src, err := ioutil.TempFile("", "")
src, err := os.CreateTemp("", "")
require.NoError(t, err)
t.Cleanup(func() {
err := os.RemoveAll(src.Name())
assert.NoError(t, err)
})
err = ioutil.WriteFile(src.Name(), []byte("Contents"), 0600)
err = os.WriteFile(src.Name(), []byte("Contents"), 0600)
require.NoError(t, err)
dst, err := ioutil.TempFile("", "")
dst, err := os.CreateTemp("", "")
require.NoError(t, err)
t.Cleanup(func() {
err := os.RemoveAll(dst.Name())
@ -35,18 +34,18 @@ func TestCopyFile(t *testing.T) {
func TestCopyFile_Permissions(t *testing.T) {
const perms = os.FileMode(0700)
src, err := ioutil.TempFile("", "")
src, err := os.CreateTemp("", "")
require.NoError(t, err)
t.Cleanup(func() {
err := os.RemoveAll(src.Name())
assert.NoError(t, err)
})
err = ioutil.WriteFile(src.Name(), []byte("Contents"), 0600)
err = os.WriteFile(src.Name(), []byte("Contents"), 0600)
require.NoError(t, err)
err = os.Chmod(src.Name(), perms)
require.NoError(t, err)
dst, err := ioutil.TempFile("", "")
dst, err := os.CreateTemp("", "")
require.NoError(t, err)
t.Cleanup(func() {
err := os.RemoveAll(dst.Name())
@ -65,7 +64,7 @@ func TestCopyFile_Permissions(t *testing.T) {
// Test case where destination directory doesn't exist.
func TestCopyFile_NonExistentDestDir(t *testing.T) {
// nolint:gosec
src, err := ioutil.TempFile("", "")
src, err := os.CreateTemp("", "")
require.NoError(t, err)
t.Cleanup(func() {
err := os.RemoveAll(src.Name())
@ -82,7 +81,7 @@ func TestCopyRecursive_NonExistentDest(t *testing.T) {
err := os.MkdirAll(filepath.Join(src, "data"), 0750)
require.NoError(t, err)
// nolint:gosec
err = ioutil.WriteFile(filepath.Join(src, "data", "file.txt"), []byte("Test"), 0644)
err = os.WriteFile(filepath.Join(src, "data", "file.txt"), []byte("Test"), 0644)
require.NoError(t, err)
dstParent := t.TempDir()
@ -101,7 +100,7 @@ func TestCopyRecursive_ExistentDest(t *testing.T) {
err := os.MkdirAll(filepath.Join(src, "data"), 0750)
require.NoError(t, err)
// nolint:gosec
err = ioutil.WriteFile(filepath.Join(src, "data", "file.txt"), []byte("Test"), 0644)
err = os.WriteFile(filepath.Join(src, "data", "file.txt"), []byte("Test"), 0644)
require.NoError(t, err)
dst := t.TempDir()
@ -139,10 +138,10 @@ func compareDirs(t *testing.T, src, dst string) {
}
// nolint:gosec
srcData, err := ioutil.ReadFile(srcPath)
srcData, err := os.ReadFile(srcPath)
require.NoError(t, err)
// nolint:gosec
dstData, err := ioutil.ReadFile(dstPath)
dstData, err := os.ReadFile(dstPath)
require.NoError(t, err)
require.Equal(t, srcData, dstData)

View File

@ -1,7 +1,6 @@
package fs
import (
"io/ioutil"
"os"
"testing"
@ -17,7 +16,7 @@ func TestExists_NonExistent(t *testing.T) {
}
func TestExists_Existent(t *testing.T) {
f, err := ioutil.TempFile("", "")
f, err := os.CreateTemp("", "")
require.NoError(t, err)
t.Cleanup(func() {
err := os.Remove(f.Name())

View File

@ -2,7 +2,7 @@ package httpclient
import (
"fmt"
"io/ioutil"
"io"
"strings"
"testing"
@ -20,14 +20,14 @@ func TestCountBytesReader(t *testing.T) {
for index, tc := range tcs {
t.Run(fmt.Sprintf("Test CountBytesReader %d", index), func(t *testing.T) {
body := ioutil.NopCloser(strings.NewReader(tc.body))
body := io.NopCloser(strings.NewReader(tc.body))
var actualBytesRead int64
readCloser := CountBytesReader(body, func(bytesRead int64) {
actualBytesRead = bytesRead
})
bodyBytes, err := ioutil.ReadAll(readCloser)
bodyBytes, err := io.ReadAll(readCloser)
require.NoError(t, err)
err = readCloser.Close()
require.NoError(t, err)

View File

@ -4,7 +4,7 @@ import (
"context"
"errors"
"fmt"
"io/ioutil"
"io"
"net/http"
"strings"
"testing"
@ -27,7 +27,7 @@ func TestResponseLimitMiddleware(t *testing.T) {
for _, tc := range tcs {
t.Run(fmt.Sprintf("Test ResponseLimitMiddleware with limit: %d", tc.limit), func(t *testing.T) {
finalRoundTripper := httpclient.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusOK, Request: req, Body: ioutil.NopCloser(strings.NewReader("dummy"))}, nil
return &http.Response{StatusCode: http.StatusOK, Request: req, Body: io.NopCloser(strings.NewReader("dummy"))}, nil
})
mw := ResponseLimitMiddleware(tc.limit)
@ -46,7 +46,7 @@ func TestResponseLimitMiddleware(t *testing.T) {
require.NotNil(t, res.Body)
require.NoError(t, res.Body.Close())
bodyBytes, err := ioutil.ReadAll(res.Body)
bodyBytes, err := io.ReadAll(res.Body)
if err != nil {
require.EqualError(t, tc.err, err.Error())
} else {

View File

@ -2,7 +2,7 @@ package httpclientprovider
import (
"bytes"
"io/ioutil"
"io"
"net/http"
"github.com/grafana/grafana-plugin-sdk-go/backend/httpclient"
@ -18,7 +18,7 @@ func (c *testContext) createRoundTripper(name string) http.RoundTripper {
return &http.Response{
StatusCode: http.StatusOK,
Request: req,
Body: ioutil.NopCloser(bytes.NewBufferString("")),
Body: io.NopCloser(bytes.NewBufferString("")),
}, nil
})
}

View File

@ -3,7 +3,7 @@ package httpclient
import (
"errors"
"fmt"
"io/ioutil"
"io"
"strings"
"testing"
@ -23,10 +23,10 @@ func TestMaxBytesReader(t *testing.T) {
}
for _, tc := range tcs {
t.Run(fmt.Sprintf("Test MaxBytesReader with limit: %d", tc.limit), func(t *testing.T) {
body := ioutil.NopCloser(strings.NewReader("dummy"))
body := io.NopCloser(strings.NewReader("dummy"))
readCloser := MaxBytesReader(body, tc.limit)
bodyBytes, err := ioutil.ReadAll(readCloser)
bodyBytes, err := io.ReadAll(readCloser)
if err != nil {
require.EqualError(t, tc.err, err.Error())
} else {

View File

@ -7,7 +7,6 @@ package log
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
@ -46,7 +45,7 @@ func init() {
// Use discard by default
format := func(w io.Writer) gokitlog.Logger {
return gokitlog.NewLogfmtLogger(gokitlog.NewSyncWriter(ioutil.Discard))
return gokitlog.NewLogfmtLogger(gokitlog.NewSyncWriter(io.Discard))
}
logger := level.NewFilter(format(os.Stderr), level.AllowInfo())
root = newManager(logger)
@ -205,9 +204,12 @@ func (cl *ConcreteLogger) New(ctx ...interface{}) *ConcreteLogger {
// name plus additional contextual information, you must use the
// Logger interface New method for it to work as expected.
// Example creating a shared logger:
// requestLogger := log.New("request-logger")
//
// requestLogger := log.New("request-logger")
//
// Example creating a contextual logger:
// contextualLogger := requestLogger.New("username", "user123")
//
// contextualLogger := requestLogger.New("username", "user123")
func New(ctx ...interface{}) *ConcreteLogger {
if len(ctx) == 0 {
return root.New()

View File

@ -5,7 +5,7 @@ import (
"context"
"encoding/json"
"errors"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"runtime"
@ -84,7 +84,7 @@ func TestMetrics(t *testing.T) {
ch := make(chan httpResp)
ticker := time.NewTicker(2 * time.Second)
ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
buf, err := ioutil.ReadAll(r.Body)
buf, err := io.ReadAll(r.Body)
if err != nil {
t.Logf("Fake HTTP handler received an error: %s", err.Error())
ch <- httpResp{

View File

@ -3,7 +3,7 @@ package statscollector
import (
"context"
"encoding/json"
"io/ioutil"
"io"
"net/http"
"time"
@ -107,7 +107,7 @@ func (s *Service) detectPrometheusVariant(ctx context.Context, ds *datasources.D
return "unknown", nil
}
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
s.log.Error("Failed to read Prometheus build info", "error", err)
return "", err

View File

@ -4,7 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"io"
"net/http"
"strings"
@ -54,7 +54,7 @@ func (s *SocialBase) httpGet(client *http.Client, url string) (response httpGetR
}
}()
body, err := ioutil.ReadAll(r.Body)
body, err := io.ReadAll(r.Body)
if err != nil {
return
}

View File

@ -7,7 +7,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/mail"
"regexp"
@ -259,7 +259,7 @@ func (s *SocialGenericOAuth) extractFromToken(token *oauth2.Token) *UserInfoJson
s.log.Warn("Failed closing zlib reader", "error", err)
}
}()
rawJSON, err = ioutil.ReadAll(fr)
rawJSON, err = io.ReadAll(fr)
if err != nil {
s.log.Error("Error decompressing payload", "error", err)
return nil

View File

@ -5,8 +5,8 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"context"
@ -388,7 +388,7 @@ func (ss *SocialService) GetOAuthHttpClient(name string) (*http.Client, error) {
}
if info.TlsClientCa != "" {
caCert, err := ioutil.ReadFile(info.TlsClientCa)
caCert, err := os.ReadFile(info.TlsClientCa)
if err != nil {
logger.Error("Failed to setup TlsClientCa", "oauth", name, "error", err)
return nil, fmt.Errorf("failed to setup TlsClientCa: %w", err)

View File

@ -19,8 +19,8 @@ import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"runtime"
"github.com/grafana/grafana/pkg/infra/log"
@ -54,7 +54,7 @@ func stack(skip int) []byte {
// We can ignore the gosec G304 warning on this one because `file`
// comes from the runtime.Caller() function.
// nolint:gosec
data, err := ioutil.ReadFile(file)
data, err := os.ReadFile(file)
if err != nil {
continue
}

View File

@ -3,7 +3,6 @@ package grpcplugin
import (
"fmt"
"io"
"io/ioutil"
"log"
glog "github.com/grafana/grafana/pkg/infra/log"
@ -159,5 +158,5 @@ func (lw logWrapper) StandardLogger(ops *hclog.StandardLoggerOptions) *log.Logge
// Return a value that conforms to io.Writer, which can be passed into log.SetOutput()
func (lw logWrapper) StandardWriter(opts *hclog.StandardLoggerOptions) io.Writer {
return ioutil.Discard
return io.Discard
}

View File

@ -11,7 +11,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
@ -125,7 +124,7 @@ func (i *Installer) Install(ctx context.Context, pluginID, version, pluginsDir,
i.log.Debugf("Installing plugin\nfrom: %s\ninto: %s", pluginZipURL, pluginsDir)
// Create temp file for downloading zip file
tmpFile, err := ioutil.TempFile("", "*.zip")
tmpFile, err := os.CreateTemp("", "*.zip")
if err != nil {
return fmt.Errorf("%v: %w", "failed to create temporary file", err)
}
@ -288,7 +287,7 @@ func (i *Installer) sendRequestGetBytes(URL string, subPaths ...string) ([]byte,
i.log.Warn("Failed to close stream", "err", err)
}
}()
return ioutil.ReadAll(bodyReader)
return io.ReadAll(bodyReader)
}
func (i *Installer) sendRequest(URL string, subPaths ...string) (io.ReadCloser, error) {
@ -342,7 +341,7 @@ func (i *Installer) createRequest(URL string, subPaths ...string) (*http.Request
func (i *Installer) handleResponse(res *http.Response) (io.ReadCloser, error) {
if res.StatusCode/100 == 4 {
body, err := ioutil.ReadAll(res.Body)
body, err := io.ReadAll(res.Body)
defer func() {
if err := res.Body.Close(); err != nil {
i.log.Warn("Failed to close response body", "err", err)
@ -676,12 +675,12 @@ func toPluginDTO(pluginDir, pluginID string) (InstalledPlugin, error) {
// It's safe to ignore gosec warning G304 since the file path suffix is hardcoded
// nolint:gosec
data, err := ioutil.ReadFile(distPluginDataPath)
data, err := os.ReadFile(distPluginDataPath)
if err != nil {
pluginDataPath := filepath.Join(pluginDir, pluginID, "plugin.json")
// It's safe to ignore gosec warning G304 since the file path suffix is hardcoded
// nolint:gosec
data, err = ioutil.ReadFile(pluginDataPath)
data, err = os.ReadFile(pluginDataPath)
if err != nil {
return InstalledPlugin{}, errors.New("Could not find dist/plugin.json or plugin.json on " + pluginID + " in " + pluginDir)
}

View File

@ -8,7 +8,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/url"
"os"
"path"
@ -29,7 +28,8 @@ import (
)
// Soon we can fetch keys from:
// https://grafana.com/api/plugins/ci/keys
//
// https://grafana.com/api/plugins/ci/keys
const publicKeyText = `-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: OpenPGP.js v4.10.1
Comment: https://openpgpjs.org
@ -116,7 +116,7 @@ func Calculate(mlog log.Logger, plugin *plugins.Plugin) (plugins.Signature, erro
// nolint:gosec
// We can ignore the gosec G304 warning on this one because `manifestPath` is based
// on plugin the folder structure on disk and not user input.
byteValue, err := ioutil.ReadFile(manifestPath)
byteValue, err := os.ReadFile(manifestPath)
if err != nil || len(byteValue) < 10 {
mlog.Debug("Plugin is unsigned", "id", plugin.ID)
return plugins.Signature{

View File

@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
@ -233,7 +232,7 @@ func (s *Server) writePIDFile() {
// Retrieve the PID and write it to file.
pid := strconv.Itoa(os.Getpid())
if err := ioutil.WriteFile(s.pidFile, []byte(pid), 0644); err != nil {
if err := os.WriteFile(s.pidFile, []byte(pid), 0644); err != nil {
s.log.Error("Failed to write pidfile", "error", err)
os.Exit(1)
}

View File

@ -3,7 +3,7 @@ package alerting
import (
"context"
"encoding/json"
"io/ioutil"
"os"
"testing"
"github.com/google/go-cmp/cmp"
@ -34,7 +34,7 @@ func TestAlertingUsageStats(t *testing.T) {
var createFake = func(file string) *simplejson.Json {
// Ignore gosec warning G304 since it's a test
// nolint:gosec
content, err := ioutil.ReadFile(file)
content, err := os.ReadFile(file)
require.NoError(t, err, "expected to be able to read file")
j, err := simplejson.NewJson(content)
@ -104,7 +104,7 @@ func TestParsingAlertRuleSettings(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
var settings json.Marshaler
if tc.file != "" {
content, err := ioutil.ReadFile(tc.file)
content, err := os.ReadFile(tc.file)
require.NoError(t, err, "expected to be able to read file")
settings, err = simplejson.NewJson(content)

View File

@ -3,7 +3,7 @@ package alerting
import (
"context"
"errors"
"io/ioutil"
"os"
"testing"
"time"
@ -27,7 +27,7 @@ func TestAlertRuleExtraction(t *testing.T) {
defaultDs := &datasources.DataSource{Id: 12, OrgId: 1, Name: "I am default", IsDefault: true, Uid: "def-uid"}
graphite2Ds := &datasources.DataSource{Id: 15, OrgId: 1, Name: "graphite2", Uid: "graphite2-uid"}
json, err := ioutil.ReadFile("./testdata/graphite-alert.json")
json, err := os.ReadFile("./testdata/graphite-alert.json")
require.Nil(t, err)
dsPermissions := permissions.NewMockDatasourcePermissionService()
@ -117,7 +117,7 @@ func TestAlertRuleExtraction(t *testing.T) {
})
t.Run("Panels missing id should return error", func(t *testing.T) {
panelWithoutID, err := ioutil.ReadFile("./testdata/panels-missing-id.json")
panelWithoutID, err := os.ReadFile("./testdata/panels-missing-id.json")
require.Nil(t, err)
dashJSON, err := simplejson.NewJson(panelWithoutID)
@ -133,7 +133,7 @@ func TestAlertRuleExtraction(t *testing.T) {
})
t.Run("Panels missing id should return error", func(t *testing.T) {
panelWithIDZero, err := ioutil.ReadFile("./testdata/panel-with-id-0.json")
panelWithIDZero, err := os.ReadFile("./testdata/panel-with-id-0.json")
require.Nil(t, err)
dashJSON, err := simplejson.NewJson(panelWithIDZero)
@ -149,7 +149,7 @@ func TestAlertRuleExtraction(t *testing.T) {
})
t.Run("Cannot save panel with query that is referenced by legacy alerting", func(t *testing.T) {
panelWithQuery, err := ioutil.ReadFile("./testdata/panel-with-bad-query-id.json")
panelWithQuery, err := os.ReadFile("./testdata/panel-with-bad-query-id.json")
require.Nil(t, err)
dashJSON, err := simplejson.NewJson(panelWithQuery)
require.Nil(t, err)
@ -163,7 +163,7 @@ func TestAlertRuleExtraction(t *testing.T) {
})
t.Run("Panel does not have datasource configured, use the default datasource", func(t *testing.T) {
panelWithoutSpecifiedDatasource, err := ioutil.ReadFile("./testdata/panel-without-specified-datasource.json")
panelWithoutSpecifiedDatasource, err := os.ReadFile("./testdata/panel-without-specified-datasource.json")
require.Nil(t, err)
dashJSON, err := simplejson.NewJson(panelWithoutSpecifiedDatasource)
@ -183,7 +183,7 @@ func TestAlertRuleExtraction(t *testing.T) {
})
t.Run("Parse alerts from dashboard without rows", func(t *testing.T) {
json, err := ioutil.ReadFile("./testdata/v5-dashboard.json")
json, err := os.ReadFile("./testdata/v5-dashboard.json")
require.Nil(t, err)
dashJSON, err := simplejson.NewJson(json)
@ -210,7 +210,7 @@ func TestAlertRuleExtraction(t *testing.T) {
err = sqlStore.CreateAlertNotificationCommand(context.Background(), &secondNotification)
require.Nil(t, err)
json, err := ioutil.ReadFile("./testdata/influxdb-alert.json")
json, err := os.ReadFile("./testdata/influxdb-alert.json")
require.Nil(t, err)
dashJSON, err := simplejson.NewJson(json)
@ -236,7 +236,7 @@ func TestAlertRuleExtraction(t *testing.T) {
})
t.Run("Should be able to extract collapsed panels", func(t *testing.T) {
json, err := ioutil.ReadFile("./testdata/collapsed-panels.json")
json, err := os.ReadFile("./testdata/collapsed-panels.json")
require.Nil(t, err)
dashJSON, err := simplejson.NewJson(json)
@ -255,7 +255,7 @@ func TestAlertRuleExtraction(t *testing.T) {
})
t.Run("Parse and validate dashboard without id and containing an alert", func(t *testing.T) {
json, err := ioutil.ReadFile("./testdata/dash-without-id.json")
json, err := os.ReadFile("./testdata/dash-without-id.json")
require.Nil(t, err)
dashJSON, err := simplejson.NewJson(json)
@ -275,7 +275,7 @@ func TestAlertRuleExtraction(t *testing.T) {
})
t.Run("Extract data source given new DataSourceRef object model", func(t *testing.T) {
json, err := ioutil.ReadFile("./testdata/panel-with-datasource-ref.json")
json, err := os.ReadFile("./testdata/panel-with-datasource-ref.json")
require.Nil(t, err)
dashJSON, err := simplejson.NewJson(json)
@ -308,7 +308,7 @@ func TestFilterPermissionsErrors(t *testing.T) {
// mock data
defaultDs := &datasources.DataSource{Id: 12, OrgId: 1, Name: "I am default", IsDefault: true, Uid: "def-uid"}
json, err := ioutil.ReadFile("./testdata/graphite-alert.json")
json, err := os.ReadFile("./testdata/graphite-alert.json")
require.Nil(t, err)
dashJSON, err := simplejson.NewJson(json)
require.Nil(t, err)

View File

@ -6,7 +6,6 @@ import (
"encoding/base64"
"encoding/json"
"encoding/pem"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
@ -66,7 +65,7 @@ func TestVerifyUsingJWKSetFile(t *testing.T) {
configure := func(t *testing.T, cfg *setting.Cfg) {
t.Helper()
file, err := ioutil.TempFile(os.TempDir(), "jwk-*.json")
file, err := os.CreateTemp(os.TempDir(), "jwk-*.json")
require.NoError(t, err)
t.Cleanup(func() {
if err := os.Remove(file.Name()); err != nil {
@ -402,7 +401,7 @@ func scenarioRunner(fn scenarioFunc, cbs ...configureFunc) func(t *testing.T) {
func configurePKIXPublicKeyFile(t *testing.T, cfg *setting.Cfg) {
t.Helper()
file, err := ioutil.TempFile(os.TempDir(), "public-key-*.pem")
file, err := os.CreateTemp(os.TempDir(), "public-key-*.pem")
require.NoError(t, err)
t.Cleanup(func() {
if err := os.Remove(file.Name()); err != nil {

View File

@ -9,7 +9,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
@ -83,7 +82,7 @@ func (s *AuthService) initKeySet() error {
}
}()
data, err := ioutil.ReadAll(file)
data, err := io.ReadAll(file)
if err != nil {
return err
}

View File

@ -2,7 +2,7 @@ package service
import (
"context"
"io/ioutil"
"os"
"path/filepath"
"testing"
@ -144,7 +144,7 @@ func TestImportDashboardService(t *testing.T) {
func loadTestDashboard(ctx context.Context, req *plugindashboards.LoadPluginDashboardRequest) (*plugindashboards.LoadPluginDashboardResponse, error) {
// It's safe to ignore gosec warning G304 since this is a test and arguments comes from test configuration.
// nolint:gosec
bytes, err := ioutil.ReadFile(filepath.Join("testdata", req.Reference))
bytes, err := os.ReadFile(filepath.Join("testdata", req.Reference))
if err != nil {
return nil, err
}

View File

@ -3,7 +3,7 @@ package service
import (
"context"
"encoding/json"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"testing"
@ -449,7 +449,7 @@ func TestService_GetHttpTransport(t *testing.T) {
err := res.Body.Close()
require.NoError(t, err)
})
body, err := ioutil.ReadAll(res.Body)
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
bodyStr := string(body)
require.Equal(t, "Ok", bodyStr)

View File

@ -3,7 +3,6 @@ package export
import (
"context"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
@ -108,7 +107,7 @@ func (ch *commitHelper) add(opts commitOptions) error {
}
}
err = ioutil.WriteFile(b.fpath, body, 0644)
err = os.WriteFile(b.fpath, body, 0644)
if err != nil {
return err
}

View File

@ -3,7 +3,7 @@ package export
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
@ -13,7 +13,7 @@ import (
func exportDashboardThumbnails(helper *commitHelper, job *gitExportJob) error {
alias := make(map[string]string, 100)
aliasLookup, err := ioutil.ReadFile(filepath.Join(helper.orgDir, "root-alias.json"))
aliasLookup, err := os.ReadFile(filepath.Join(helper.orgDir, "root-alias.json"))
if err != nil {
return fmt.Errorf("missing dashboard alias files (must export dashboards first)")
}

View File

@ -1,7 +1,7 @@
package featuremgmt
import (
"io/ioutil"
"os"
"gopkg.in/yaml.v2"
)
@ -23,7 +23,7 @@ func readConfigFile(filename string) (*configBody, error) {
// Can ignore gosec G304 because the file path is forced within config subfolder
//nolint:gosec
yamlFile, err := ioutil.ReadFile(filename)
yamlFile, err := os.ReadFile(filename)
if err != nil {
return cfg, err
}

View File

@ -4,7 +4,6 @@ import (
"bytes"
"fmt"
"html/template"
"io/ioutil"
"os"
"path/filepath"
"strings"
@ -61,7 +60,7 @@ func TestFeatureToggleFiles(t *testing.T) {
func verifyAndGenerateFile(t *testing.T, fpath string, gen string) {
// nolint:gosec
// We can ignore the gosec G304 warning since this is a test and the function is only called explicitly above
body, err := ioutil.ReadFile(fpath)
body, err := os.ReadFile(fpath)
if err == nil {
if diff := cmp.Diff(gen, string(body)); diff != "" {
str := fmt.Sprintf("body mismatch (-want +got):\n%s\n", diff)

View File

@ -5,9 +5,9 @@ import (
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"math"
"net"
"os"
"strconv"
"strings"
"time"
@ -101,7 +101,7 @@ func (server *Server) Dial() error {
for _, caCertFile := range strings.Split(server.Config.RootCACert, " ") {
// nolint:gosec
// We can ignore the gosec G304 warning on this one because `caCertFile` comes from ldap config.
pem, err := ioutil.ReadFile(caCertFile)
pem, err := os.ReadFile(caCertFile)
if err != nil {
return err
}

View File

@ -2,7 +2,7 @@ package ldap
import (
"fmt"
"io/ioutil"
"os"
"sync"
"github.com/BurntSushi/toml"
@ -123,7 +123,7 @@ func readConfig(configFile string) (*Config, error) {
// nolint:gosec
// We can ignore the gosec G304 warning on this one because `filename` comes from grafana configuration file
fileBytes, err := ioutil.ReadFile(configFile)
fileBytes, err := os.ReadFile(configFile)
if err != nil {
return nil, fmt.Errorf("%v: %w", "Failed to load LDAP config file", err)
}

View File

@ -5,7 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/url"
"os"
@ -1124,7 +1124,7 @@ func (s *DryRunRuleStorage) ListChannelRules(_ context.Context, _ int64) ([]pipe
// HandlePipelineConvertTestHTTP ...
func (g *GrafanaLive) HandlePipelineConvertTestHTTP(c *models.ReqContext) response.Response {
body, err := ioutil.ReadAll(c.Req.Body)
body, err := io.ReadAll(c.Req.Body)
if err != nil {
return response.Error(http.StatusInternalServerError, "Error reading body", err)
}
@ -1169,7 +1169,7 @@ func (g *GrafanaLive) HandlePipelineConvertTestHTTP(c *models.ReqContext) respon
// HandleChannelRulesPostHTTP ...
func (g *GrafanaLive) HandleChannelRulesPostHTTP(c *models.ReqContext) response.Response {
body, err := ioutil.ReadAll(c.Req.Body)
body, err := io.ReadAll(c.Req.Body)
if err != nil {
return response.Error(http.StatusInternalServerError, "Error reading body", err)
}
@ -1189,7 +1189,7 @@ func (g *GrafanaLive) HandleChannelRulesPostHTTP(c *models.ReqContext) response.
// HandleChannelRulesPutHTTP ...
func (g *GrafanaLive) HandleChannelRulesPutHTTP(c *models.ReqContext) response.Response {
body, err := ioutil.ReadAll(c.Req.Body)
body, err := io.ReadAll(c.Req.Body)
if err != nil {
return response.Error(http.StatusInternalServerError, "Error reading body", err)
}
@ -1212,7 +1212,7 @@ func (g *GrafanaLive) HandleChannelRulesPutHTTP(c *models.ReqContext) response.R
// HandleChannelRulesDeleteHTTP ...
func (g *GrafanaLive) HandleChannelRulesDeleteHTTP(c *models.ReqContext) response.Response {
body, err := ioutil.ReadAll(c.Req.Body)
body, err := io.ReadAll(c.Req.Body)
if err != nil {
return response.Error(http.StatusInternalServerError, "Error reading body", err)
}
@ -1259,7 +1259,7 @@ func (g *GrafanaLive) HandleWriteConfigsListHTTP(c *models.ReqContext) response.
// HandleWriteConfigsPostHTTP ...
func (g *GrafanaLive) HandleWriteConfigsPostHTTP(c *models.ReqContext) response.Response {
body, err := ioutil.ReadAll(c.Req.Body)
body, err := io.ReadAll(c.Req.Body)
if err != nil {
return response.Error(http.StatusInternalServerError, "Error reading body", err)
}
@ -1279,7 +1279,7 @@ func (g *GrafanaLive) HandleWriteConfigsPostHTTP(c *models.ReqContext) response.
// HandleWriteConfigsPutHTTP ...
func (g *GrafanaLive) HandleWriteConfigsPutHTTP(c *models.ReqContext) response.Response {
body, err := ioutil.ReadAll(c.Req.Body)
body, err := io.ReadAll(c.Req.Body)
if err != nil {
return response.Error(http.StatusInternalServerError, "Error reading body", err)
}
@ -1323,7 +1323,7 @@ func (g *GrafanaLive) HandleWriteConfigsPutHTTP(c *models.ReqContext) response.R
// HandleWriteConfigsDeleteHTTP ...
func (g *GrafanaLive) HandleWriteConfigsDeleteHTTP(c *models.ReqContext) response.Response {
body, err := ioutil.ReadAll(c.Req.Body)
body, err := io.ReadAll(c.Req.Body)
if err != nil {
return response.Error(http.StatusInternalServerError, "Error reading body", err)
}

View File

@ -3,7 +3,7 @@ package pipeline
import (
"context"
"flag"
"io/ioutil"
"os"
"path/filepath"
"testing"
"time"
@ -19,7 +19,7 @@ func loadTestJson(t testing.TB, file string) []byte {
t.Helper()
// Safe to disable, this is a test.
// nolint:gosec
content, err := ioutil.ReadFile(filepath.Join("testdata", file+".json"))
content, err := os.ReadFile(filepath.Join("testdata", file+".json"))
require.NoError(t, err, "expected to be able to read file")
require.True(t, len(content) > 0)
return content

View File

@ -5,7 +5,6 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
@ -240,7 +239,7 @@ func (f *FileStorage) readRules() (ChannelRules, error) {
ruleFile := f.ruleFilePath()
// Safe to ignore gosec warning G304.
// nolint:gosec
ruleBytes, err := ioutil.ReadFile(ruleFile)
ruleBytes, err := os.ReadFile(ruleFile)
if err != nil {
return ChannelRules{}, fmt.Errorf("can't read pipeline rules: %s: %w", f.ruleFilePath(), err)
}
@ -309,7 +308,7 @@ func (f *FileStorage) readWriteConfigs() (WriteConfigs, error) {
filePath := f.writeConfigsFilePath()
// Safe to ignore gosec warning G304.
// nolint:gosec
bytes, err := ioutil.ReadFile(filePath)
bytes, err := os.ReadFile(filePath)
if err != nil {
return WriteConfigs{}, fmt.Errorf("can't read %s file: %w", filePath, err)
}

View File

@ -4,7 +4,7 @@ import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
@ -18,7 +18,7 @@ func loadTestData(tb testing.TB, file string) []byte {
tb.Helper()
// Safe to disable, this is a test.
// nolint:gosec
content, err := ioutil.ReadFile(filepath.Join("testdata", file+".txt"))
content, err := os.ReadFile(filepath.Join("testdata", file+".txt"))
require.NoError(tb, err, "expected to be able to read file")
require.True(tb, len(content) > 0)
return content
@ -28,7 +28,7 @@ func checkTestData(t *testing.T, file string) *backend.DataResponse {
t.Helper()
// Safe to disable, this is a test.
// nolint:gosec
content, err := ioutil.ReadFile(filepath.Join("testdata", file+".txt"))
content, err := os.ReadFile(filepath.Join("testdata", file+".txt"))
require.NoError(t, err, "expected to be able to read file")
require.True(t, len(content) > 0)
@ -143,13 +143,13 @@ func TestConverter_Convert_NumFrameFields(t *testing.T) {
frameJSON, err := json.MarshalIndent(frame, "", " ")
require.NoError(t, err)
if *update {
if err := ioutil.WriteFile(goldenFile, frameJSON, 0600); err != nil {
if err := os.WriteFile(goldenFile, frameJSON, 0600); err != nil {
t.Fatal(err)
}
}
// Safe to disable, this is a test.
// nolint:gosec
want, err := ioutil.ReadFile(goldenFile)
want, err := os.ReadFile(goldenFile)
if err != nil {
t.Fatal(err)
}
@ -223,13 +223,13 @@ func TestConverter_Convert_NumFrameFields_LabelsColumn(t *testing.T) {
frameJSON, err := json.MarshalIndent(frame, "", " ")
require.NoError(t, err)
if *update {
if err := ioutil.WriteFile(goldenFile, frameJSON, 0600); err != nil {
if err := os.WriteFile(goldenFile, frameJSON, 0600); err != nil {
t.Fatal(err)
}
}
// Safe to disable, this is a test.
// nolint:gosec
want, err := ioutil.ReadFile(goldenFile)
want, err := os.ReadFile(goldenFile)
if err != nil {
t.Fatal(err)
}

View File

@ -3,8 +3,8 @@ package main
import (
"encoding/json"
"flag"
"io/ioutil"
"log"
"os"
"strings"
)
@ -22,7 +22,7 @@ func main() {
}
//nolint
b, err := ioutil.ReadFile(input)
b, err := os.ReadFile(input)
if err != nil {
log.Fatal(err)
}
@ -101,7 +101,7 @@ func main() {
log.Fatal(err)
}
err = ioutil.WriteFile(output, out, 0644)
err = os.WriteFile(output, out, 0644)
if err != nil {
log.Fatal(err)
}

View File

@ -3,7 +3,7 @@ package definitions
import (
"encoding/json"
"errors"
"io/ioutil"
"os"
"strings"
"testing"
@ -808,10 +808,10 @@ alertmanager_config: |
func Test_GettableUserConfigRoundtrip(t *testing.T) {
// raw contains secret fields. We'll unmarshal, re-marshal, and ensure
// the fields are not redacted.
yamlEncoded, err := ioutil.ReadFile("alertmanager_test_artifact.yaml")
yamlEncoded, err := os.ReadFile("alertmanager_test_artifact.yaml")
require.Nil(t, err)
jsonEncoded, err := ioutil.ReadFile("alertmanager_test_artifact.json")
jsonEncoded, err := os.ReadFile("alertmanager_test_artifact.json")
require.Nil(t, err)
// test GettableUserConfig (yamlDecode -> jsonEncode)
@ -1031,7 +1031,7 @@ routes:
}
func Test_Marshaling_Validation(t *testing.T) {
jsonEncoded, err := ioutil.ReadFile("alertmanager_test_artifact.json")
jsonEncoded, err := os.ReadFile("alertmanager_test_artifact.json")
require.Nil(t, err)
var tmp GettableUserConfig

View File

@ -1,7 +1,6 @@
package channels
import (
"io/ioutil"
"os"
"testing"
@ -92,7 +91,7 @@ Labels:
`
func templateForTests(t *testing.T) *template.Template {
f, err := ioutil.TempFile("/tmp", "template")
f, err := os.CreateTemp("/tmp", "template")
require.NoError(t, err)
defer func(f *os.File) {
_ = f.Close()

View File

@ -2,7 +2,6 @@ package channels
import (
"context"
"io/ioutil"
"net/url"
"os"
"testing"
@ -56,7 +55,7 @@ func TestDefaultTemplateString(t *testing.T) {
},
}
f, err := ioutil.TempFile("/tmp", "template")
f, err := os.CreateTemp("/tmp", "template")
require.NoError(t, err)
defer func(f *os.File) {
_ = f.Close()

View File

@ -4,7 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"io/ioutil"
"io"
"net/http"
"net/url"
"strings"
@ -268,7 +268,7 @@ func TestTeamsNotifier(t *testing.T) {
expBody, err := json.Marshal(c.expMsg)
require.NoError(t, err)
body, err := ioutil.ReadAll(clientStub.lastRequest.Body)
body, err := io.ReadAll(clientStub.lastRequest.Body)
require.NoError(t, err)
require.JSONEq(t, string(expBody), string(body))
})
@ -311,6 +311,6 @@ func newMockClient(resp *mockResponse) *mockClient {
func makeResponse(status int, body string) *http.Response {
return &http.Response{
StatusCode: status,
Body: ioutil.NopCloser(strings.NewReader(body)),
Body: io.NopCloser(strings.NewReader(body)),
}
}

View File

@ -36,7 +36,7 @@ func PersistTemplates(cfg *api.PostableUserConfig, path string) ([]string, bool,
// Check if the template file already exists and if it has changed
// We can safely ignore gosec here as we've previously checked the filename is clean
// nolint:gosec
if tmpl, err := ioutil.ReadFile(file); err == nil && string(tmpl) == content {
if tmpl, err := os.ReadFile(file); err == nil && string(tmpl) == content {
// Templates file is the same we have, no-op and continue.
continue
} else if err != nil && !os.IsNotExist(err) {
@ -45,7 +45,7 @@ func PersistTemplates(cfg *api.PostableUserConfig, path string) ([]string, bool,
// We can safely ignore gosec here as we've previously checked the filename is clean
// nolint:gosec
if err := ioutil.WriteFile(file, []byte(content), 0644); err != nil {
if err := os.WriteFile(file, []byte(content), 0644); err != nil {
return nil, false, fmt.Errorf("unable to create Alertmanager template file %q: %s", file, err)
}

View File

@ -3,6 +3,7 @@ package notifier
import (
"errors"
"io/ioutil"
"os"
"path/filepath"
"testing"
@ -71,7 +72,7 @@ func TestPersistTemplates(t *testing.T) {
dir := t.TempDir()
// Write "existing files"
for name, content := range tt.existingTemplates {
err := ioutil.WriteFile(filepath.Join(dir, name), []byte(content), 0644)
err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0644)
require.NoError(t, err)
}
c := &api.PostableUserConfig{TemplateFiles: tt.templates}
@ -87,7 +88,7 @@ func TestPersistTemplates(t *testing.T) {
}
// Safe to disable, this is a test.
// nolint:gosec
content, err := ioutil.ReadFile(filepath.Join(dir, f.Name()))
content, err := os.ReadFile(filepath.Join(dir, f.Name()))
// nolint:gosec
require.NoError(t, err)
files[f.Name()] = string(content)

View File

@ -2,7 +2,6 @@ package notifier
import (
"context"
"io/ioutil"
"os"
"path/filepath"
"testing"
@ -24,7 +23,7 @@ func TestFileStore_FilepathFor_DirectoryNotExist(t *testing.T) {
r, err := fs.FilepathFor(context.Background(), filekey)
require.NoError(t, err)
require.Equal(t, filePath, r)
f, err := ioutil.ReadFile(filepath.Clean(filePath))
f, err := os.ReadFile(filepath.Clean(filePath))
require.NoError(t, err)
require.Equal(t, "silence1,silence3", string(f))
require.NoError(t, os.Remove(filePath))
@ -44,7 +43,7 @@ func TestFileStore_FilepathFor(t *testing.T) {
r, err := fs.FilepathFor(context.Background(), filekey)
require.NoError(t, err)
require.Equal(t, filePath, r)
f, err := ioutil.ReadFile(filepath.Clean(filePath))
f, err := os.ReadFile(filepath.Clean(filePath))
require.NoError(t, err)
require.Equal(t, "silence1,silence2", string(f))
require.NoError(t, os.Remove(filePath))
@ -56,7 +55,7 @@ func TestFileStore_FilepathFor(t *testing.T) {
r, err := fs.FilepathFor(context.Background(), filekey)
require.NoError(t, err)
require.Equal(t, filePath, r)
f, err := ioutil.ReadFile(filepath.Clean(filePath))
f, err := os.ReadFile(filepath.Clean(filePath))
require.NoError(t, err)
require.Equal(t, "silence1,silence3", string(f))
require.NoError(t, os.Remove(filePath))
@ -68,7 +67,7 @@ func TestFileStore_FilepathFor(t *testing.T) {
r, err := fs.FilepathFor(context.Background(), filekey)
require.NoError(t, err)
require.Equal(t, filePath, r)
_, err = ioutil.ReadFile(filepath.Clean(filePath))
_, err = os.ReadFile(filepath.Clean(filePath))
require.Error(t, err)
}
}

View File

@ -2,7 +2,7 @@ package sender
import (
"encoding/json"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"sync"
@ -71,7 +71,7 @@ func (am *FakeExternalAlertmanager) Alerts() amv2.PostableAlerts {
func (am *FakeExternalAlertmanager) Handler() func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
b, err := io.ReadAll(r.Body)
require.NoError(am.t, err)
a := amv2.PostableAlerts{}

View File

@ -2,7 +2,7 @@ package notifications
import (
"context"
"io/ioutil"
"os"
"testing"
"github.com/grafana/grafana/pkg/models"
@ -62,9 +62,9 @@ func TestEmailIntegrationTest(t *testing.T) {
sentMsg := <-ns.mailQueue
require.Equal(t, sentMsg.From, "Grafana Admin <from@address.com>")
require.Equal(t, sentMsg.To[0], "asdf@asdf.com")
err = ioutil.WriteFile("../../../tmp/test_email.html", []byte(sentMsg.Body["text/html"]), 0777)
err = os.WriteFile("../../../tmp/test_email.html", []byte(sentMsg.Body["text/html"]), 0777)
require.NoError(t, err)
err = ioutil.WriteFile("../../../tmp/test_email.txt", []byte(sentMsg.Body["text/plain"]), 0777)
err = os.WriteFile("../../../tmp/test_email.txt", []byte(sentMsg.Body["text/plain"]), 0777)
require.NoError(t, err)
})
})

View File

@ -5,7 +5,7 @@ import (
"context"
"crypto/tls"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"time"
@ -88,7 +88,7 @@ func (ns *NotificationService) sendWebRequestSync(ctx context.Context, webhook *
}
}()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}

View File

@ -5,6 +5,7 @@ import (
"fmt"
"io/fs"
"io/ioutil"
"os"
"path/filepath"
"strings"
@ -65,7 +66,7 @@ func (cr *rulesConfigReader) parseConfig(path string, file fs.FileInfo) (*Alerti
filename, _ := filepath.Abs(filepath.Join(path, file.Name()))
// nolint:gosec
// We can ignore the gosec G304 warning on this one because `filename` comes from ps.Cfg.ProvisioningPath
yamlFile, err := ioutil.ReadFile(filename)
yamlFile, err := os.ReadFile(filename)
if err != nil {
return nil, err
}

View File

@ -24,7 +24,7 @@ func (cr *configReader) parseConfigs(file os.FileInfo) ([]*config, error) {
// nolint:gosec
// We can ignore the gosec G304 warning on this one because `filename` comes from ps.Cfg.ProvisioningPath
yamlFile, err := ioutil.ReadFile(filename)
yamlFile, err := os.ReadFile(filename)
if err != nil {
return nil, err
}

View File

@ -4,7 +4,7 @@ import (
"context"
"errors"
"fmt"
"io/ioutil"
"io"
"os"
"path/filepath"
"strings"
@ -397,7 +397,7 @@ func (fr *FileReader) readDashboardFromFile(path string, lastModified time.Time,
}
}()
all, err := ioutil.ReadAll(reader)
all, err := io.ReadAll(reader)
if err != nil {
return nil, err
}

View File

@ -55,7 +55,7 @@ func (cr *configReader) parseDatasourceConfig(path string, file os.FileInfo) (*c
// nolint:gosec
// We can ignore the gosec G304 warning on this one because `filename` comes from ps.Cfg.ProvisioningPath
yamlFile, err := ioutil.ReadFile(filename)
yamlFile, err := os.ReadFile(filename)
if err != nil {
return nil, err
}

View File

@ -70,7 +70,7 @@ func (cr *configReader) parseNotificationConfig(path string, file os.FileInfo) (
// nolint:gosec
// We can ignore the gosec G304 warning on this one because `filename` comes from ps.Cfg.ProvisioningPath
yamlFile, err := ioutil.ReadFile(filename)
yamlFile, err := os.ReadFile(filename)
if err != nil {
return nil, err
}

View File

@ -73,7 +73,7 @@ func (cr *configReaderImpl) parsePluginConfig(path string, file os.FileInfo) (*p
// nolint:gosec
// We can ignore the gosec G304 warning on this one because `filename` comes from ps.Cfg.ProvisioningPath
yamlFile, err := ioutil.ReadFile(filename)
yamlFile, err := os.ReadFile(filename)
if err != nil {
return nil, err
}

View File

@ -3,7 +3,6 @@ package values
import (
"errors"
"fmt"
"io/ioutil"
"os"
"testing"
@ -311,7 +310,7 @@ func TestValues_readFile(t *testing.T) {
Val StringValue `yaml:"val"`
}
f, err := ioutil.TempFile(os.TempDir(), "file expansion *")
f, err := os.CreateTemp(os.TempDir(), "file expansion *")
require.NoError(t, err)
file := f.Name()

View File

@ -5,7 +5,6 @@ import (
"context"
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"runtime"
@ -356,7 +355,7 @@ func (i *searchIndex) reportSizeOfIndexDiskBackup(orgID int64) {
defer cancel()
// create a temp directory to store the index
tmpDir, err := ioutil.TempDir("", "grafana.dashboard_index")
tmpDir, err := os.MkdirTemp("", "grafana.dashboard_index")
if err != nil {
i.logger.Error("can't create temp dir", "error", err)
return

View File

@ -4,7 +4,7 @@ import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"os"
"github.com/grafana/grafana/pkg/infra/log"
)
@ -13,7 +13,7 @@ var tlslog = log.New("tls_mysql")
func makeCert(config DatabaseConfig) (*tls.Config, error) {
rootCertPool := x509.NewCertPool()
pem, err := ioutil.ReadFile(config.CaCertPath)
pem, err := os.ReadFile(config.CaCertPath)
if err != nil {
return nil, fmt.Errorf("could not read DB CA Cert path %q: %w", config.CaCertPath, err)
}

View File

@ -3,7 +3,6 @@ package store
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
@ -32,7 +31,7 @@ func LoadStorageConfig(cfg *setting.Cfg, features featuremgmt.FeatureToggles) (*
if _, err := os.Stat(fpath); err == nil {
// nolint:gosec
// We can ignore the gosec G304 warning since the path is hardcoded above
body, err := ioutil.ReadFile(fpath)
body, err := os.ReadFile(fpath)
if err != nil {
return g, err
}
@ -96,7 +95,7 @@ func (c *GlobalStorageConfig) save() error {
if err != nil {
return err
}
return ioutil.WriteFile(c.filepath, out, 0600)
return os.WriteFile(c.filepath, out, 0600)
}
type RootStorageConfig struct {

View File

@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
@ -114,7 +113,7 @@ func (s *standardStorageService) doUpload(c *models.ReqContext) response.Respons
if err != nil {
return response.Error(500, "Internal Server Error", err)
}
data, err := ioutil.ReadAll(file)
data, err := io.ReadAll(file)
if err != nil {
return response.Error(500, "Internal Server Error", err)
}

View File

@ -3,7 +3,7 @@ package store
import (
"bytes"
"context"
"io/ioutil"
"os"
"path/filepath"
"testing"
@ -24,9 +24,9 @@ var (
AllowUnsanitizedSvgUpload: true,
},
}
htmlBytes, _ = ioutil.ReadFile("testdata/page.html")
jpgBytes, _ = ioutil.ReadFile("testdata/image.jpg")
svgBytes, _ = ioutil.ReadFile("testdata/image.svg")
htmlBytes, _ = os.ReadFile("testdata/page.html")
jpgBytes, _ = os.ReadFile("testdata/image.jpg")
svgBytes, _ = os.ReadFile("testdata/image.svg")
dummyUser = &user.SignedInUser{OrgId: 1}
allowAllAuthService = newStaticStorageAuthService(func(ctx context.Context, user *user.SignedInUser, storageName string) map[string]filestorage.PathFilter {
return map[string]filestorage.PathFilter{

View File

@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
@ -388,7 +387,7 @@ func (hs *thumbService) SetImage(c *models.ReqContext) {
hs.log.Info("File Size: %+v\n", handler.Size)
hs.log.Info("MIME Header: %+v\n", handler.Header)
fileBytes, err := ioutil.ReadAll(file)
fileBytes, err := io.ReadAll(file)
if err != nil {
fmt.Println(err)
c.JSON(400, map[string]string{"error": "error reading file"})

View File

@ -3,7 +3,7 @@ package updatechecker
import (
"context"
"encoding/json"
"io/ioutil"
"io"
"net/http"
"strings"
"sync"
@ -68,7 +68,7 @@ func (s *GrafanaService) checkForUpdates() {
s.log.Warn("Failed to close response body", "err", err)
}
}()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
s.log.Debug("Update check failed, reading response from github.com", "error", err)
return

View File

@ -3,7 +3,7 @@ package updatechecker
import (
"context"
"encoding/json"
"io/ioutil"
"io"
"net/http"
"strings"
"sync"
@ -99,7 +99,7 @@ func (s *PluginsService) checkForUpdates(ctx context.Context) {
}
}()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
s.log.Debug("Update check failed, reading response from grafana.com", "error", err.Error())
return

View File

@ -2,7 +2,7 @@ package updatechecker
import (
"context"
"io/ioutil"
"io"
"net/http"
"strings"
"testing"
@ -190,7 +190,7 @@ func (c *fakeHTTPClient) Get(url string) (*http.Response, error) {
c.requestURL = url
resp := &http.Response{
Body: ioutil.NopCloser(strings.NewReader(c.fakeResp)),
Body: io.NopCloser(strings.NewReader(c.fakeResp)),
}
return resp, nil

View File

@ -2,7 +2,6 @@ package setting
import (
"fmt"
"io/ioutil"
"os"
"regexp"
"sort"
@ -145,7 +144,7 @@ func (e fileExpander) Expand(s string) (string, error) {
// nolint:gosec
// We can ignore the gosec G304 warning on this one because `s` comes from configuration section keys
f, err := ioutil.ReadFile(s)
f, err := os.ReadFile(s)
if err != nil {
return "", err
}

View File

@ -3,7 +3,6 @@ package setting
import (
"errors"
"fmt"
"io/ioutil"
"math/rand"
"os"
"testing"
@ -35,7 +34,7 @@ func TestExpandVar_EnvSuccessful(t *testing.T) {
}
func TestExpandVar_FileSuccessful(t *testing.T) {
f, err := ioutil.TempFile(os.TempDir(), "file expansion *")
f, err := os.CreateTemp(os.TempDir(), "file expansion *")
require.NoError(t, err)
file := f.Name()

View File

@ -4,7 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"testing"
"time"
@ -62,7 +62,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) {
{
alertsURL := fmt.Sprintf("http://grafana:password@%s/api/v1/ngalert/admin_config", grafanaListedAddr)
resp := getRequest(t, alertsURL, http.StatusNotFound) // nolint
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var res map[string]interface{}
err = json.Unmarshal(b, &res)
@ -82,7 +82,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) {
alertsURL := fmt.Sprintf("http://grafana:password@%s/api/v1/ngalert/admin_config", grafanaListedAddr)
resp := postRequest(t, alertsURL, buf.String(), http.StatusBadRequest) // nolint
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var res map[string]interface{}
err = json.Unmarshal(b, &res)
@ -103,7 +103,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) {
alertsURL := fmt.Sprintf("http://grafana:password@%s/api/v1/ngalert/admin_config", grafanaListedAddr)
resp := postRequest(t, alertsURL, buf.String(), http.StatusBadRequest) // nolint
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var res map[string]interface{}
err = json.Unmarshal(b, &res)
@ -125,7 +125,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) {
alertsURL := fmt.Sprintf("http://grafana:password@%s/api/v1/ngalert/admin_config", grafanaListedAddr)
resp := postRequest(t, alertsURL, buf.String(), http.StatusCreated) // nolint
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var res map[string]interface{}
err = json.Unmarshal(b, &res)
@ -137,7 +137,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) {
{
alertsURL := fmt.Sprintf("http://grafana:password@%s/api/v1/ngalert/admin_config", grafanaListedAddr)
resp := getRequest(t, alertsURL, http.StatusOK) // nolint
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.JSONEq(t, fmt.Sprintf("{\"alertmanagers\":[\"%s\",\"%s\"], \"alertmanagersChoice\": %q}\n", fakeAM1.URL(), fakeAM2.URL(), ngmodels.ExternalAlertmanagers), string(b))
}
@ -147,7 +147,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) {
alertsURL := fmt.Sprintf("http://grafana:password@%s/api/v1/ngalert/alertmanagers", grafanaListedAddr)
require.Eventually(t, func() bool {
resp := getRequest(t, alertsURL, http.StatusOK) // nolint
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var alertmanagers apimodels.GettableAlertmanagers
@ -227,7 +227,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) {
alertsURL := fmt.Sprintf("http://admin-42:admin-42@%s/api/v1/ngalert/admin_config", grafanaListedAddr)
resp := postRequest(t, alertsURL, buf.String(), http.StatusCreated) // nolint
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var res map[string]interface{}
err = json.Unmarshal(b, &res)
@ -239,7 +239,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) {
{
alertsURL := fmt.Sprintf("http://admin-42:admin-42@%s/api/v1/ngalert/admin_config", grafanaListedAddr)
resp := getRequest(t, alertsURL, http.StatusOK) // nolint
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.JSONEq(t, fmt.Sprintf("{\"alertmanagers\":[\"%s\"], \"alertmanagersChoice\": %q}\n", fakeAM3.URL(), ngmodels.AllAlertmanagers), string(b))
}
@ -249,7 +249,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) {
alertsURL := fmt.Sprintf("http://admin-42:admin-42@%s/api/v1/ngalert/alertmanagers", grafanaListedAddr)
require.Eventually(t, func() bool {
resp := getRequest(t, alertsURL, http.StatusOK) // nolint
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var alertmanagers apimodels.GettableAlertmanagers

View File

@ -3,7 +3,7 @@ package alerting
import (
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"regexp"
"testing"
@ -87,7 +87,7 @@ func TestAlertmanagerConfigurationIsTransactional(t *testing.T) {
}
`
resp := postRequest(t, alertConfigURL, payload, http.StatusBadRequest) // nolint
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var res map[string]interface{}
require.NoError(t, json.Unmarshal(b, &res))

View File

@ -5,7 +5,7 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"regexp"
"strings"
@ -127,7 +127,7 @@ func TestAMConfigAccess(t *testing.T) {
})
require.NoError(t, err)
require.Equal(t, tc.expStatus, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Contains(t, string(b), tc.expBody)
})
@ -194,7 +194,7 @@ func TestAMConfigAccess(t *testing.T) {
})
require.NoError(t, err)
require.Equal(t, tc.expStatus, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
if tc.expStatus == http.StatusOK {
re := regexp.MustCompile(`"uid":"([\w|-]+)"`)
b = re.ReplaceAll(b, []byte(`"uid":""`))
@ -260,7 +260,7 @@ func TestAMConfigAccess(t *testing.T) {
})
require.NoError(t, err)
require.Equal(t, tc.expStatus, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
if tc.expStatus == http.StatusAccepted {
re := regexp.MustCompile(`"id":"([\w|-]+)"`)
@ -309,7 +309,7 @@ func TestAMConfigAccess(t *testing.T) {
require.Equal(t, tc.expStatus, resp.StatusCode)
require.NoError(t, err)
if tc.expStatus == http.StatusOK {
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
blob = b
}
@ -379,7 +379,7 @@ func TestAMConfigAccess(t *testing.T) {
})
require.NoError(t, err)
require.Equal(t, tc.expStatus, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
if tc.expStatus == http.StatusOK {
unconsumedSilenceIdx++
@ -410,7 +410,7 @@ func TestAlertAndGroupsQuery(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, http.StatusUnauthorized, resp.StatusCode)
require.JSONEq(t, `{"message": "Unauthorized"}`, string(b))
@ -435,7 +435,7 @@ func TestAlertAndGroupsQuery(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, http.StatusUnauthorized, resp.StatusCode)
@ -454,7 +454,7 @@ func TestAlertAndGroupsQuery(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
require.JSONEq(t, "[]", string(b))
@ -470,7 +470,7 @@ func TestAlertAndGroupsQuery(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
@ -529,7 +529,7 @@ func TestAlertAndGroupsQuery(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
@ -704,7 +704,7 @@ func TestDeleteFolderWithRules(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
@ -781,7 +781,7 @@ func TestDeleteFolderWithRules(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
require.JSONEq(t, `{"message":"folder cannot be deleted: folder contains alert rules"}`, string(b))
@ -799,7 +799,7 @@ func TestDeleteFolderWithRules(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
require.JSONEq(t, `{"id":1,"message":"Folder default deleted","title":"default"}`, string(b))
@ -815,7 +815,7 @@ func TestDeleteFolderWithRules(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
@ -1155,7 +1155,7 @@ func TestAlertRuleCRUD(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, resp.StatusCode, 202)
@ -1322,7 +1322,7 @@ func TestAlertRuleCRUD(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, resp.StatusCode, 202)
@ -1428,7 +1428,7 @@ func TestAlertRuleCRUD(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, resp.StatusCode, 202)
@ -1500,7 +1500,7 @@ func TestAlertRuleCRUD(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, resp.StatusCode, 202)
@ -1617,7 +1617,7 @@ func TestAlertRuleCRUD(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, resp.StatusCode, 202)
@ -1702,7 +1702,7 @@ func TestAlertRuleCRUD(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, resp.StatusCode, 202)
@ -1774,7 +1774,7 @@ func TestAlertRuleCRUD(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, http.StatusAccepted, resp.StatusCode)
@ -1793,7 +1793,7 @@ func TestAlertRuleCRUD(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, http.StatusAccepted, resp.StatusCode)
@ -1822,7 +1822,7 @@ func TestAlertmanagerStatus(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
require.JSONEq(t, `
@ -1904,7 +1904,7 @@ func TestQuota(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, resp.StatusCode, 202)
@ -2022,7 +2022,7 @@ func TestQuota(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, resp.StatusCode, 202)
@ -2318,7 +2318,7 @@ func TestEval(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
res := Response{}
err = json.Unmarshal(b, &res)
@ -2501,7 +2501,7 @@ func TestEval(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
res := Response{}
err = json.Unmarshal(b, &res)

View File

@ -3,7 +3,7 @@ package alerting
import (
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"testing"
@ -40,7 +40,7 @@ func TestAvailableChannels(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)

View File

@ -7,7 +7,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net"
"net/http"
@ -59,7 +58,7 @@ func TestTestReceivers(t *testing.T) {
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
res := Response{}
err = json.Unmarshal(b, &res)
@ -110,7 +109,7 @@ func TestTestReceivers(t *testing.T) {
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var result apimodels.TestReceiversResult
@ -189,7 +188,7 @@ func TestTestReceivers(t *testing.T) {
require.NoError(t, resp.Body.Close())
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var result apimodels.TestReceiversResult
@ -276,7 +275,7 @@ func TestTestReceivers(t *testing.T) {
})
require.Equal(t, http.StatusRequestTimeout, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var result apimodels.TestReceiversResult
@ -375,7 +374,7 @@ func TestTestReceivers(t *testing.T) {
})
require.Equal(t, http.StatusMultiStatus, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var result apimodels.TestReceiversResult
@ -478,7 +477,7 @@ func TestTestReceiversAlertCustomization(t *testing.T) {
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var result apimodels.TestReceiversResult
@ -568,7 +567,7 @@ func TestTestReceiversAlertCustomization(t *testing.T) {
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var result apimodels.TestReceiversResult
@ -655,7 +654,7 @@ func TestTestReceiversAlertCustomization(t *testing.T) {
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var result apimodels.TestReceiversResult
@ -752,7 +751,7 @@ func TestNotificationChannels(t *testing.T) {
// There are no notification channel config initially - so it returns the default configuration.
alertsURL := fmt.Sprintf("http://grafana:password@%s/api/alertmanager/grafana/config/api/v1/alerts", grafanaListedAddr)
resp := getRequest(t, alertsURL, http.StatusOK) // nolint
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.JSONEq(t, defaultAlertmanagerConfigJSON, string(b))
}
@ -812,14 +811,14 @@ func TestNotificationChannels(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 202, resp.StatusCode)
require.JSONEq(t, `{"message":"configuration deleted; the default is applied"}`, string(b))
alertsURL := fmt.Sprintf("http://grafana:password@%s/api/alertmanager/grafana/config/api/v1/alerts", grafanaListedAddr)
resp = getRequest(t, alertsURL, http.StatusOK) // nolint
b, err = ioutil.ReadAll(resp.Body)
b, err = io.ReadAll(resp.Body)
require.NoError(t, err)
require.JSONEq(t, defaultAlertmanagerConfigJSON, string(b))
}

View File

@ -5,7 +5,7 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"sort"
"testing"
@ -74,7 +74,7 @@ func TestPrometheusRules(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
require.JSONEq(t, `{"status": "success", "data": {"groups": []}}`, string(b))
@ -149,7 +149,7 @@ func TestPrometheusRules(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, resp.StatusCode, 202)
@ -203,7 +203,7 @@ func TestPrometheusRules(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, 400, resp.StatusCode)
@ -222,7 +222,7 @@ func TestPrometheusRules(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
@ -275,7 +275,7 @@ func TestPrometheusRules(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
require.JSONEq(t, `
@ -414,7 +414,7 @@ func TestPrometheusRulesFilterByDashboard(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, resp.StatusCode, 202)
@ -501,7 +501,7 @@ func TestPrometheusRulesFilterByDashboard(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
@ -518,7 +518,7 @@ func TestPrometheusRulesFilterByDashboard(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
@ -535,7 +535,7 @@ func TestPrometheusRulesFilterByDashboard(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
@ -552,7 +552,7 @@ func TestPrometheusRulesFilterByDashboard(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
@ -569,7 +569,7 @@ func TestPrometheusRulesFilterByDashboard(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
@ -587,7 +587,7 @@ func TestPrometheusRulesFilterByDashboard(t *testing.T) {
require.NoError(t, err)
})
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var res map[string]interface{}
require.NoError(t, json.Unmarshal(b, &res))
@ -605,7 +605,7 @@ func TestPrometheusRulesFilterByDashboard(t *testing.T) {
require.NoError(t, err)
})
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var res map[string]interface{}
require.NoError(t, json.Unmarshal(b, &res))
@ -657,7 +657,7 @@ func TestPrometheusRulesPermissions(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
@ -687,7 +687,7 @@ func TestPrometheusRulesPermissions(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
@ -712,7 +712,7 @@ func TestPrometheusRulesPermissions(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)

View File

@ -3,7 +3,7 @@ package alerting
import (
"encoding/json"
"fmt"
"io/ioutil"
"io"
"math/rand"
"net/http"
"testing"
@ -64,7 +64,7 @@ func TestAlertRulePermissions(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, resp.StatusCode, 200)
@ -187,7 +187,7 @@ func TestAlertRulePermissions(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err = ioutil.ReadAll(resp.Body)
b, err = io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, resp.StatusCode, 200)
@ -261,7 +261,7 @@ func TestAlertRulePermissions(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, resp.StatusCode, 200)
@ -604,7 +604,7 @@ func TestRulerRulesFilterByDashboard(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
@ -622,7 +622,7 @@ func TestRulerRulesFilterByDashboard(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
@ -640,7 +640,7 @@ func TestRulerRulesFilterByDashboard(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
@ -657,7 +657,7 @@ func TestRulerRulesFilterByDashboard(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
@ -675,7 +675,7 @@ func TestRulerRulesFilterByDashboard(t *testing.T) {
err := resp.Body.Close()
require.NoError(t, err)
})
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
@ -693,7 +693,7 @@ func TestRulerRulesFilterByDashboard(t *testing.T) {
require.NoError(t, err)
})
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var res map[string]interface{}
require.NoError(t, json.Unmarshal(b, &res))
@ -711,7 +711,7 @@ func TestRulerRulesFilterByDashboard(t *testing.T) {
require.NoError(t, err)
})
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var res map[string]interface{}
require.NoError(t, json.Unmarshal(b, &res))

Some files were not shown because too many files have changed in this diff Show More