diff --git a/aws/rds/rds.go b/aws/rds/rds.go index 01054b72cf..8a25def69a 100644 --- a/aws/rds/rds.go +++ b/aws/rds/rds.go @@ -21,7 +21,6 @@ import ( "encoding/pem" "fmt" "io" - "io/ioutil" "net/http" "github.com/google/wire" @@ -79,7 +78,7 @@ func (cf *CertFetcher) Fetch(ctx context.Context) ([]*x509.Certificate, error) { if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("fetch RDS certificates: HTTP %s", resp.Status) } - pemData, err := ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 1 << 20}) // limit to 1MiB + pemData, err := io.ReadAll(&io.LimitedReader{R: resp.Body, N: 1 << 20}) // limit to 1MiB if err != nil { return nil, fmt.Errorf("fetch RDS certificates: %v", err) } diff --git a/azure/azuredb/azuredb.go b/azure/azuredb/azuredb.go index 46a4cd2e26..6100397175 100644 --- a/azure/azuredb/azuredb.go +++ b/azure/azuredb/azuredb.go @@ -21,7 +21,6 @@ import ( "encoding/pem" "fmt" "io" - "io/ioutil" "net/http" "golang.org/x/net/context/ctxhttp" @@ -70,7 +69,7 @@ func (cf *CertFetcher) Fetch(ctx context.Context) ([]*x509.Certificate, error) { if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("fetch Azure certificates: HTTP %s", resp.Status) } - pemData, err := ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 1 << 20}) // limit to 1MiB + pemData, err := io.ReadAll(&io.LimitedReader{R: resp.Body, N: 1 << 20}) // limit to 1MiB if err != nil { return nil, fmt.Errorf("fetch Azure certificates: %v", err) } diff --git a/blob/blob.go b/blob/blob.go index 4593448045..b0237fcc22 100644 --- a/blob/blob.go +++ b/blob/blob.go @@ -70,7 +70,6 @@ import ( "fmt" "hash" "io" - "io/ioutil" "log" "mime" "net/http" @@ -732,7 +731,7 @@ func (b *Bucket) ReadAll(ctx context.Context, key string) (_ []byte, err error) return nil, err } defer r.Close() - return ioutil.ReadAll(r) + return io.ReadAll(r) } // Download writes the content of a blob into an io.Writer w. diff --git a/blob/drivertest/drivertest.go b/blob/drivertest/drivertest.go index e96d678948..81d4d07fc3 100644 --- a/blob/drivertest/drivertest.go +++ b/blob/drivertest/drivertest.go @@ -23,7 +23,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "log" "net/http" "net/url" @@ -2123,12 +2122,14 @@ func testConcurrentWriteAndRead(t *testing.T, newHarness HarnessMaker) { var wg sync.WaitGroup + errs := make(chan error, numKeys) + // Write all blobs concurrently. for k := 0; k < numKeys; k++ { wg.Add(1) go func(key int) { if err := b.WriteAll(ctx, blobName(key), keyData[key], nil); err != nil { - t.Fatal(err) + errs <- fmt.Errorf("WriteAll key=%v: %w", key, err) } wg.Done() }(k) @@ -2136,21 +2137,34 @@ func testConcurrentWriteAndRead(t *testing.T, newHarness HarnessMaker) { } wg.Wait() + close(errs) + + for err := range errs { + t.Fatalf("got error from concurrent blob write: %v", err) + } + + errs = make(chan error, numKeys) + // Read all blobs concurrently and verify that they contain the expected data. for k := 0; k < numKeys; k++ { wg.Add(1) go func(key int) { buf, err := b.ReadAll(ctx, blobName(key)) if err != nil { - t.Fatal(err) - } - if !bytes.Equal(buf, keyData[key]) { - t.Errorf("read data mismatch for key %d", key) + errs <- err + } else if !bytes.Equal(buf, keyData[key]) { + errs <- fmt.Errorf("read data mismatch for key %d", key) } wg.Done() }(k) } wg.Wait() + + close(errs) + + for err := range errs { + t.Fatalf("got error from concurrent blob write: %v", err) + } } // testUploadDownload tests that Upload and Download work. For many drivers, @@ -2275,7 +2289,7 @@ func testKeys(t *testing.T, newHarness HarnessMaker) { if resp.StatusCode != 200 { t.Errorf("got status code %d, want 200", resp.StatusCode) } - got, err := ioutil.ReadAll(resp.Body) + got, err := io.ReadAll(resp.Body) if err != nil { t.Fatal(err) } @@ -2463,7 +2477,7 @@ func testSignedURL(t *testing.T, newHarness HarnessMaker) { success := resp.StatusCode >= 200 && resp.StatusCode < 300 if success != test.wantSuccess { t.Errorf("PUT to %q with ContentType %q got status code %d, wanted 2xx? %v", test.urlDescription, test.contentType, resp.StatusCode, test.wantSuccess) - gotBody, _ := ioutil.ReadAll(resp.Body) + gotBody, _ := io.ReadAll(resp.Body) t.Errorf(string(gotBody)) } } @@ -2487,10 +2501,10 @@ func testSignedURL(t *testing.T, newHarness HarnessMaker) { success := resp.StatusCode >= 200 && resp.StatusCode < 300 if success != test.wantSuccess { t.Errorf("GET to %q got status code %d, want 2xx? %v", test.urlDescription, resp.StatusCode, test.wantSuccess) - gotBody, _ := ioutil.ReadAll(resp.Body) + gotBody, _ := io.ReadAll(resp.Body) t.Errorf(string(gotBody)) } else if success { - gotBody, err := ioutil.ReadAll(resp.Body) + gotBody, err := io.ReadAll(resp.Body) if err != nil { t.Errorf("GET to %q failed to read response body: %v", test.urlDescription, err) } else if gotBodyStr := string(gotBody); gotBodyStr != contents { @@ -2519,7 +2533,7 @@ func testSignedURL(t *testing.T, newHarness HarnessMaker) { defer resp.Body.Close() success := resp.StatusCode >= 200 && resp.StatusCode < 300 if success != test.wantSuccess { - gotBody, _ := ioutil.ReadAll(resp.Body) + gotBody, _ := io.ReadAll(resp.Body) t.Errorf(string(gotBody)) t.Fatalf("DELETE to %q got status code %d, want 2xx? %v", test.urlDescription, resp.StatusCode, test.wantSuccess) } @@ -2534,7 +2548,7 @@ func testSignedURL(t *testing.T, newHarness HarnessMaker) { defer resp.Body.Close() if resp.StatusCode != 404 { t.Errorf("GET after DELETE got status code %d, want 404", resp.StatusCode) - gotBody, _ := ioutil.ReadAll(resp.Body) + gotBody, _ := io.ReadAll(resp.Body) t.Errorf(string(gotBody)) } } diff --git a/blob/example_test.go b/blob/example_test.go index 9401622694..3e7fd969c8 100644 --- a/blob/example_test.go +++ b/blob/example_test.go @@ -18,7 +18,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "log" "os" @@ -570,7 +569,7 @@ func ExampleAttributes_As() { } func newTempDir() (string, func()) { - dir, err := ioutil.TempDir("", "go-cloud-blob-example") + dir, err := os.MkdirTemp("", "go-cloud-blob-example") if err != nil { panic(err) } diff --git a/blob/fileblob/example_test.go b/blob/fileblob/example_test.go index 9a638ca859..c7b5706981 100644 --- a/blob/fileblob/example_test.go +++ b/blob/fileblob/example_test.go @@ -17,7 +17,6 @@ package fileblob_test import ( "context" "fmt" - "io/ioutil" "log" "os" "path/filepath" @@ -46,7 +45,7 @@ func ExampleOpenBucket() { func Example_openBucketFromURL() { // Create a temporary directory. - dir, err := ioutil.TempDir("", "go-cloud-fileblob-example") + dir, err := os.MkdirTemp("", "go-cloud-fileblob-example") if err != nil { log.Fatal(err) } diff --git a/blob/fileblob/fileblob.go b/blob/fileblob/fileblob.go index 44d5f41f33..2801e0ffc6 100644 --- a/blob/fileblob/fileblob.go +++ b/blob/fileblob/fileblob.go @@ -73,7 +73,6 @@ import ( "hash" "io" "io/fs" - "io/ioutil" "net/url" "os" "path/filepath" @@ -222,7 +221,7 @@ func (o *URLOpener) forParams(ctx context.Context, q url.Values) (*Options, erro if err != nil { return nil, err } - sk, err := ioutil.ReadFile(keyPath) + sk, err := os.ReadFile(keyPath) if err != nil { return nil, err } diff --git a/blob/fileblob/fileblob_test.go b/blob/fileblob/fileblob_test.go index a4e808c9ad..ff332ed2fe 100644 --- a/blob/fileblob/fileblob_test.go +++ b/blob/fileblob/fileblob_test.go @@ -19,7 +19,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "net/http/httptest" "net/url" @@ -215,22 +214,16 @@ func BenchmarkFileblob(b *testing.B) { // File-specific unit tests. func TestNewBucket(t *testing.T) { t.Run("BucketDirMissing", func(t *testing.T) { - dir, err := ioutil.TempDir("", "fileblob") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() + _, gotErr := OpenBucket(filepath.Join(dir, "notfound"), nil) if gotErr == nil { t.Errorf("got nil want error") } }) t.Run("BucketDirMissingWithCreateDir", func(t *testing.T) { - dir, err := ioutil.TempDir("", "fileblob") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() + b, gotErr := OpenBucket(filepath.Join(dir, "notfound"), &Options{CreateDir: true}) if gotErr != nil { t.Errorf("got error %v", gotErr) @@ -244,11 +237,12 @@ func TestNewBucket(t *testing.T) { } }) t.Run("BucketIsFile", func(t *testing.T) { - f, err := ioutil.TempFile("", "fileblob") + dir := t.TempDir() + + f, err := os.CreateTemp(dir, "fileblob") if err != nil { t.Fatal(err) } - defer os.Remove(f.Name()) _, gotErr := OpenBucket(f.Name(), nil) if gotErr == nil { t.Errorf("got nil want error") @@ -257,11 +251,8 @@ func TestNewBucket(t *testing.T) { } func TestSignedURLReturnsUnimplementedWithNoURLSigner(t *testing.T) { - dir, err := ioutil.TempDir("", "fileblob") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() + b, err := OpenBucket(dir, nil) if err != nil { t.Fatal(err) @@ -352,15 +343,15 @@ func TestOpenBucketFromURL(t *testing.T) { if err := os.MkdirAll(filepath.Join(dir, subdir), os.ModePerm); err != nil { t.Fatal(err) } - if err := ioutil.WriteFile(filepath.Join(dir, "myfile.txt"), []byte("hello world"), 0666); err != nil { + if err := os.WriteFile(filepath.Join(dir, "myfile.txt"), []byte("hello world"), 0666); err != nil { t.Fatal(err) } // To avoid making another temp dir, use the bucket directory to hold the secret key file. secretKeyPath := filepath.Join(dir, "secret.key") - if err := ioutil.WriteFile(secretKeyPath, []byte("secret key"), 0666); err != nil { + if err := os.WriteFile(secretKeyPath, []byte("secret key"), 0666); err != nil { t.Fatal(err) } - if err := ioutil.WriteFile(filepath.Join(dir, subdir, "myfileinsubdir.txt"), []byte("hello world in subdir"), 0666); err != nil { + if err := os.WriteFile(filepath.Join(dir, subdir, "myfileinsubdir.txt"), []byte("hello world in subdir"), 0666); err != nil { t.Fatal(err) } // Convert dir to a URL path, adding a leading "/" if needed on Windows. @@ -460,10 +451,8 @@ func TestListAtRoot(t *testing.T) { } defer b.Close() - dir, err := ioutil.TempDir("", "fileblob") - if err != nil { - t.Fatalf("Got error creating temp dir: %#v", err) - } + dir := t.TempDir() + f, err := os.Create(filepath.Join(dir, "file.txt")) if err != nil { t.Fatalf("Got error creating file: %#v", err) @@ -487,11 +476,8 @@ func TestListAtRoot(t *testing.T) { } func TestSkipMetadata(t *testing.T) { - dir, err := ioutil.TempDir("", "fileblob*") - if err != nil { - t.Fatalf("Got error creating temp dir: %#v", err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() + dirpath := filepath.ToSlash(dir) if os.PathSeparator != '/' && !strings.HasPrefix(dirpath, "/") { dirpath = "/" + dirpath diff --git a/blob/gcsblob/gcsblob.go b/blob/gcsblob/gcsblob.go index 8ff2890834..42491cc848 100644 --- a/blob/gcsblob/gcsblob.go +++ b/blob/gcsblob/gcsblob.go @@ -63,7 +63,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "net/url" "os" @@ -248,7 +247,7 @@ func (o *URLOpener) forParams(ctx context.Context, q url.Values) (*Options, *gcp } } if keyPath := q.Get("private_key_path"); keyPath != "" { - pk, err := ioutil.ReadFile(keyPath) + pk, err := os.ReadFile(keyPath) if err != nil { return nil, nil, err } @@ -345,7 +344,7 @@ type bucket struct { opts *Options } -var emptyBody = ioutil.NopCloser(strings.NewReader("")) +var emptyBody = io.NopCloser(strings.NewReader("")) // reader reads a GCS object. It implements driver.Reader. type reader struct { diff --git a/blob/gcsblob/gcsblob_test.go b/blob/gcsblob/gcsblob_test.go index b56122308a..eefde6aa9c 100644 --- a/blob/gcsblob/gcsblob_test.go +++ b/blob/gcsblob/gcsblob_test.go @@ -19,7 +19,7 @@ import ( "errors" "flag" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "os" @@ -74,7 +74,7 @@ func newHarness(ctx context.Context, t *testing.T) (drivertest.Harness, error) { *pathToPrivateKey = filepath.Join(usr.HomeDir, "Downloads", "gcs-private-key.pem") } // Use a real private key for signing URLs during -record. - pk, err := ioutil.ReadFile(*pathToPrivateKey) + pk, err := os.ReadFile(*pathToPrivateKey) if err != nil { t.Fatalf("Couldn't find private key at %v: %v", *pathToPrivateKey, err) } @@ -456,7 +456,7 @@ func TestPreconditions(t *testing.T) { t.Fatal(err) } defer reader.Close() - gotBytes, err := ioutil.ReadAll(reader) + gotBytes, err := io.ReadAll(reader) if err != nil { t.Fatal(err) } @@ -519,7 +519,7 @@ func TestURLOpenerForParams(t *testing.T) { // Create a file for use as a dummy private key file. privateKey := []byte("some content") - pkFile, err := ioutil.TempFile("", "my-private-key") + pkFile, err := os.CreateTemp("", "my-private-key") if err != nil { t.Fatal(err) } @@ -639,12 +639,12 @@ func TestOpenBucketFromURL(t *testing.T) { cleanup := setup.FakeGCPDefaultCredentials(t) defer cleanup() - pkFile, err := ioutil.TempFile("", "my-private-key") + pkFile, err := os.CreateTemp("", "my-private-key") if err != nil { t.Fatal(err) } defer os.Remove(pkFile.Name()) - if err := ioutil.WriteFile(pkFile.Name(), []byte("key"), 0666); err != nil { + if err := os.WriteFile(pkFile.Name(), []byte("key"), 0666); err != nil { t.Fatal(err) } diff --git a/blob/gcsblob/iam_test.go b/blob/gcsblob/iam_test.go index 897a0e8a61..86a7345c43 100644 --- a/blob/gcsblob/iam_test.go +++ b/blob/gcsblob/iam_test.go @@ -69,7 +69,7 @@ func TestIAMCredentialsClient(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { c := credentialsClient{err: test.connectErr, client: test.mockClient} - makeSignBytesFn := c.CreateMakeSignBytesWith(nil, serviceAccountID) + makeSignBytesFn := c.CreateMakeSignBytesWith(context.TODO(), serviceAccountID) signBytesFn := makeSignBytesFn(nil) // Our mocks don't read any context. haveOutput, haveErr := signBytesFn(test.input) diff --git a/blob/s3blob/s3blob.go b/blob/s3blob/s3blob.go index 304e2f7c2d..680cb8d946 100644 --- a/blob/s3blob/s3blob.go +++ b/blob/s3blob/s3blob.go @@ -151,11 +151,11 @@ const ( func toServerSideEncryptionType(value string) (typesv2.ServerSideEncryption, error) { for _, sseType := range typesv2.ServerSideEncryptionAes256.Values() { - if strings.ToLower(string(sseType)) == strings.ToLower(value) { + if strings.EqualFold(string(sseType), value) { return sseType, nil } } - return "", fmt.Errorf("'%s' is not a valid value for '%s'", value, sseTypeParamKey) + return "", fmt.Errorf("%q is not a valid value for %q", value, sseTypeParamKey) } // OpenBucketURL opens a blob.Bucket based on u. diff --git a/blob/s3blob/s3blob_test.go b/blob/s3blob/s3blob_test.go index b8e5ccfac6..be91ac3d5e 100644 --- a/blob/s3blob/s3blob_test.go +++ b/blob/s3blob/s3blob_test.go @@ -503,7 +503,7 @@ func TestToServerSideEncryptionType(t *testing.T) { // OK, AES256 mixed case {"Aes256", typesv2.ServerSideEncryptionAes256, nil}, // Invalid SSE type - {"invalid", "", fmt.Errorf("'invalid' is not a valid value for '%s'", sseTypeParamKey)}, + {"invalid", "", fmt.Errorf("'invalid' is not a valid value for %q", sseTypeParamKey)}, } for _, test := range tests { diff --git a/blob/wrapped_bucket_test.go b/blob/wrapped_bucket_test.go index 5877fbed70..61bd78427c 100644 --- a/blob/wrapped_bucket_test.go +++ b/blob/wrapped_bucket_test.go @@ -12,8 +12,8 @@ import ( ) func TestPrefixedBucket(t *testing.T) { - dir, cleanup := newTempDir() - defer cleanup() + dir := t.TempDir() + bucket, err := fileblob.OpenBucket(dir, nil) if err != nil { t.Fatal(err) @@ -38,8 +38,8 @@ func TestPrefixedBucket(t *testing.T) { } func TestSingleKeyBucket(t *testing.T) { - dir, cleanup := newTempDir() - defer cleanup() + dir := t.TempDir() + bucket, err := fileblob.OpenBucket(dir, nil) if err != nil { t.Fatal(err) diff --git a/docstore/awsdynamodb/dynamo.go b/docstore/awsdynamodb/dynamo.go index 6f71f15622..2df0aef081 100644 --- a/docstore/awsdynamodb/dynamo.go +++ b/docstore/awsdynamodb/dynamo.go @@ -180,17 +180,17 @@ func (c *collection) runGets(ctx context.Context, actions []*driver.Action, errs for i := 0; i < n; i++ { i := i t.Acquire() - go func() { + go func(group []*driver.Action) { defer t.Release() c.batchGet(ctx, group, errs, opts, batchSize*i, batchSize*(i+1)-1) - }() + }(group) } if n*batchSize < len(group) { t.Acquire() - go func() { + go func(group []*driver.Action) { defer t.Release() c.batchGet(ctx, group, errs, opts, batchSize*n, len(group)-1) - }() + }(group) } } t.Wait() diff --git a/docstore/gcpfirestore/fs.go b/docstore/gcpfirestore/fs.go index 5469927778..076b50f48d 100644 --- a/docstore/gcpfirestore/fs.go +++ b/docstore/gcpfirestore/fs.go @@ -83,6 +83,7 @@ import ( "gocloud.dev/internal/useragent" "google.golang.org/api/option" "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" @@ -98,7 +99,8 @@ func Dial(ctx context.Context, ts gcp.TokenSource) (*vkit.Client, func(), error) useragent.ClientOption("docstore"), } if host := os.Getenv("FIRESTORE_EMULATOR_HOST"); host != "" { - conn, err := grpc.DialContext(ctx, host, grpc.WithInsecure()) + conn, err := grpc.DialContext(ctx, host, + grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { return nil, nil, err } @@ -602,7 +604,6 @@ func (c *collection) doCommitCall(ctx context.Context, call *commitCall, errs [] j++ } } - return } func hasFollowingTransform(writes []*pb.Write, i int) bool { diff --git a/docstore/gcpfirestore/native_codec_test.go b/docstore/gcpfirestore/native_codec_test.go index adb74cea61..daa9f8651a 100644 --- a/docstore/gcpfirestore/native_codec_test.go +++ b/docstore/gcpfirestore/native_codec_test.go @@ -25,6 +25,7 @@ import ( "github.com/google/go-cmp/cmp" "google.golang.org/api/option" "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/metadata" tspb "google.golang.org/protobuf/types/known/timestamppb" ) @@ -53,7 +54,7 @@ func newNativeCodec() (*nativeCodec, error) { nc := &nativeCodec{} conn, err := grpc.Dial(l.Addr().String(), - grpc.WithInsecure(), + grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), grpc.WithUnaryInterceptor(nc.interceptUnary), grpc.WithStreamInterceptor(nc.interceptStream)) diff --git a/docstore/memdocstore/mem_test.go b/docstore/memdocstore/mem_test.go index 7532eb18a5..c9c86aaa1a 100644 --- a/docstore/memdocstore/mem_test.go +++ b/docstore/memdocstore/mem_test.go @@ -16,7 +16,6 @@ package memdocstore import ( "context" - "io/ioutil" "os" "path/filepath" "testing" @@ -164,12 +163,7 @@ func TestSortDocs(t *testing.T) { } func TestSaveAndLoad(t *testing.T) { - // Save and then load into a file. - dir, err := ioutil.TempDir("", t.Name()) - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() // Load from nonexistent file should return empty data. f := filepath.Join(dir, "saveAndLoad") diff --git a/docstore/memdocstore/urls.go b/docstore/memdocstore/urls.go index 599abfbd5d..84d3258aeb 100644 --- a/docstore/memdocstore/urls.go +++ b/docstore/memdocstore/urls.go @@ -59,9 +59,7 @@ func (o *URLOpener) OpenCollectionURL(ctx context.Context, u *url.URL) (*docstor return nil, fmt.Errorf("open collection %v: empty collection name", u) } keyName := u.Path - if strings.HasPrefix(keyName, "/") { - keyName = keyName[1:] - } + keyName = strings.TrimPrefix(keyName, "/") if keyName == "" || strings.ContainsRune(keyName, '/') { return nil, fmt.Errorf("open collection %v: invalid key name %q (must be non-empty and have no slashes)", u, keyName) } diff --git a/internal/releasehelper/releasehelper.go b/internal/releasehelper/releasehelper.go index dc0963d807..faade184f3 100644 --- a/internal/releasehelper/releasehelper.go +++ b/internal/releasehelper/releasehelper.go @@ -246,7 +246,7 @@ func main() { if len(input.Text()) > 0 && !strings.HasPrefix(input.Text(), "#") { fields := strings.Fields(input.Text()) if len(fields) != 2 { - log.Fatalf("want 2 fields, got '%s'\n", input.Text()) + log.Fatalf("want 2 fields, got %q\n", input.Text()) } // "tag" only runs if the released field is "yes". Other commands run // for every line. diff --git a/internal/releasehelper/releasehelper_test.go b/internal/releasehelper/releasehelper_test.go index a2bb5c6b88..ed7fd40240 100644 --- a/internal/releasehelper/releasehelper_test.go +++ b/internal/releasehelper/releasehelper_test.go @@ -16,7 +16,6 @@ package main import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -49,34 +48,31 @@ require ( `) func createFilesForTest(root string) error { - if err := ioutil.WriteFile(filepath.Join(root, "go.mod"), mainGomod, 0666); err != nil { + if err := os.WriteFile(filepath.Join(root, "go.mod"), mainGomod, 0666); err != nil { return err } if err := os.MkdirAll(filepath.Join(root, "submod"), 0766); err != nil { return err } - if err := ioutil.WriteFile(filepath.Join(root, "submod", "go.mod"), submodGomod, 0666); err != nil { + if err := os.WriteFile(filepath.Join(root, "submod", "go.mod"), submodGomod, 0666); err != nil { return err } if err := os.MkdirAll(filepath.Join(root, "samples"), 0766); err != nil { return err } - if err := ioutil.WriteFile(filepath.Join(root, "samples", "go.mod"), samplesGomod, 0666); err != nil { + if err := os.WriteFile(filepath.Join(root, "samples", "go.mod"), samplesGomod, 0666); err != nil { return err } return nil } func Test(t *testing.T) { - tempDir, err := ioutil.TempDir("", "releasehelper_test") - if err != nil { - t.Fatal(err) - } + tempDir := t.TempDir() + fmt.Println("temp dir:", tempDir) if err := createFilesForTest(tempDir); err != nil { t.Fatal(err) } - defer os.RemoveAll(tempDir) if err := os.Chdir(tempDir); err != nil { t.Fatal(err) @@ -86,7 +82,7 @@ func Test(t *testing.T) { gomodAddReplace("samples") samplesGomod := filepath.Join("samples", "go.mod") - c, err := ioutil.ReadFile(samplesGomod) + c, err := os.ReadFile(samplesGomod) if err != nil { t.Fatal(err) } @@ -97,26 +93,26 @@ func Test(t *testing.T) { for _, line := range replaceLines { if !strings.Contains(string(c), line) { - t.Errorf("Expected to find '%s' in samples/go.mod", line) + t.Errorf("Expected to find %q in samples/go.mod", line) } } // Drop replace lines and expect not to find them. gomodDropReplace("samples") - c, err = ioutil.ReadFile(samplesGomod) + c, err = os.ReadFile(samplesGomod) if err != nil { t.Fatal(err) } for _, line := range replaceLines { if strings.Contains(string(c), line) { - t.Errorf("Expected to not find '%s' in samples/go.mod", line) + t.Errorf("Expected to not find %q in samples/go.mod", line) } } // Set new version and check it was set as expected. gomodSetVersion("samples", "v1.8.99") - c, err = ioutil.ReadFile(samplesGomod) + c, err = os.ReadFile(samplesGomod) if err != nil { t.Fatal(err) } diff --git a/internal/testing/setup/setup.go b/internal/testing/setup/setup.go index ed0d0a0eaf..044a9c9f55 100644 --- a/internal/testing/setup/setup.go +++ b/internal/testing/setup/setup.go @@ -17,7 +17,6 @@ package setup // import "gocloud.dev/internal/testing/setup" import ( "context" "flag" - "io/ioutil" "net/http" "os" "path/filepath" @@ -267,11 +266,11 @@ func NewAzureKeyVaultTestClient(ctx context.Context, t *testing.T) (*http.Client func FakeGCPDefaultCredentials(t *testing.T) func() { const envVar = "GOOGLE_APPLICATION_CREDENTIALS" jsonCred := []byte(`{"client_id": "foo.apps.googleusercontent.com", "client_secret": "bar", "refresh_token": "baz", "type": "authorized_user"}`) - f, err := ioutil.TempFile("", "fake-gcp-creds") + f, err := os.CreateTemp("", "fake-gcp-creds") if err != nil { t.Fatal(err) } - if err := ioutil.WriteFile(f.Name(), jsonCred, 0666); err != nil { + if err := os.WriteFile(f.Name(), jsonCred, 0666); err != nil { t.Fatal(err) } oldEnvVal := os.Getenv(envVar) diff --git a/internal/website/content/howto/blob/_index.md b/internal/website/content/howto/blob/_index.md index 143a606a74..c84d4e952f 100644 --- a/internal/website/content/howto/blob/_index.md +++ b/internal/website/content/howto/blob/_index.md @@ -140,7 +140,7 @@ ignore the error because the write's failure is expected. Once you have written data to a bucket, you can read it back by creating a reader. The reader implements [`io.Reader`][], so you can use any functions -that take an `io.Reader` like `io.Copy` or `io/ioutil.ReadAll`. You must +that take an `io.Reader` like `io.Copy` or `io/io.ReadAll`. You must always close a reader after using it to avoid leaking resources. {{< goexample src="gocloud.dev/blob.ExampleBucket_NewReader" imports="0" >}} diff --git a/internal/website/content/tutorials/cli-uploader.md b/internal/website/content/tutorials/cli-uploader.md index fe5464401d..84d7e16ba6 100644 --- a/internal/website/content/tutorials/cli-uploader.md +++ b/internal/website/content/tutorials/cli-uploader.md @@ -127,7 +127,7 @@ func main() { // ... previous code omitted // Prepare the file for upload. - data, err := ioutil.ReadFile(file) + data, err := os.ReadFile(file) if err != nil { log.Fatalf("Failed to read file: %s", err) } diff --git a/postgres/postgres_test.go b/postgres/postgres_test.go index 38124f1a2b..4d287c49ad 100644 --- a/postgres/postgres_test.go +++ b/postgres/postgres_test.go @@ -18,7 +18,6 @@ import ( "bytes" "context" "fmt" - "io/ioutil" "net/url" "os" "os/exec" @@ -47,15 +46,9 @@ func TestOpen(t *testing.T) { if err != nil { t.Fatal(err) } - dir, err := ioutil.TempDir("", "gocloud_postgres_test") - if err != nil { - t.Fatal(err) - } - defer func() { - if err := os.RemoveAll(dir); err != nil { - t.Errorf("Cleaning up: %v", err) - } - }() + + dir := t.TempDir() + dataDir := filepath.Join(dir, "data") initdbCmd := exec.Command(initdbPath, "-U", currUser.Username, "-D", dataDir) initdbOutput := new(bytes.Buffer) @@ -77,7 +70,7 @@ func TestOpen(t *testing.T) { } confData := new(bytes.Buffer) fmt.Fprintf(confData, "unix_socket_directories = '%s'\n", socketDir) - err = ioutil.WriteFile(filepath.Join(dataDir, "postgresql.conf"), confData.Bytes(), 0666) + err = os.WriteFile(filepath.Join(dataDir, "postgresql.conf"), confData.Bytes(), 0666) if err != nil { t.Fatal(err) } diff --git a/pubsub/acks_test.go b/pubsub/acks_test.go index abda0a7f99..6549cb4b6a 100644 --- a/pubsub/acks_test.go +++ b/pubsub/acks_test.go @@ -159,11 +159,12 @@ func TestTooManyAcksForASingleBatchGoIntoMultipleBatches(t *testing.T) { sub := pubsub.NewSubscription(ds, nil, nil) defer sub.Shutdown(ctx) + errs := make(chan error, n) // Receive and ack the messages concurrently. recv := func() { mr, err := sub.Receive(ctx) if err != nil { - t.Fatal(err) + errs <- err } mr.Ack() } @@ -173,9 +174,15 @@ func TestTooManyAcksForASingleBatchGoIntoMultipleBatches(t *testing.T) { } wg.Wait() + close(errs) + if len(sentAckBatches) < 2 { t.Errorf("got %d batches, want at least 2", len(sentAckBatches)) } + + for err := range errs { + t.Fatalf("got error from goroutine: %v", err) + } } func TestAckDoesNotBlock(t *testing.T) { diff --git a/pubsub/gcppubsub/gcppubsub.go b/pubsub/gcppubsub/gcppubsub.go index 51fc9d0c2c..94753e832f 100644 --- a/pubsub/gcppubsub/gcppubsub.go +++ b/pubsub/gcppubsub/gcppubsub.go @@ -74,6 +74,7 @@ import ( "google.golang.org/api/option" "google.golang.org/grpc" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/credentials/oauth" "google.golang.org/grpc/status" ) @@ -308,7 +309,9 @@ func Dial(ctx context.Context, ts gcp.TokenSource) (*grpc.ClientConn, func(), er // dialEmulator opens a gRPC connection to the GCP Pub Sub API. func dialEmulator(ctx context.Context, e string) (*grpc.ClientConn, error) { - conn, err := grpc.DialContext(ctx, e, grpc.WithInsecure(), useragent.GRPCDialOption("pubsub")) + conn, err := grpc.DialContext(ctx, e, + grpc.WithTransportCredentials(insecure.NewCredentials()), + useragent.GRPCDialOption("pubsub")) if err != nil { return nil, err } diff --git a/pubsub/pub_test.go b/pubsub/pub_test.go index 4b7d1cecdb..79d9a27a82 100644 --- a/pubsub/pub_test.go +++ b/pubsub/pub_test.go @@ -16,6 +16,7 @@ package pubsub_test import ( "context" + "errors" "testing" "time" @@ -48,10 +49,12 @@ func TestTopicShutdownCanBeCanceledEvenWithHangingSend(t *testing.T) { } topic := pubsub.NewTopic(dt, nil) + errs := make(chan error, 1) + go func() { m := &pubsub.Message{} if err := topic.Send(context.Background(), m); err == nil { - t.Fatal("nil err from Send, expected context cancellation error") + errs <- errors.New("nil err from Send, expected context cancellation error") } }() @@ -72,6 +75,8 @@ func TestTopicShutdownCanBeCanceledEvenWithHangingSend(t *testing.T) { case <-done: case <-time.After(tooLong): t.Fatalf("waited too long(%v) for Shutdown(ctx) to run", tooLong) + case err := <-errs: + t.Fatalf("got error from goroutine: %v", err) } } diff --git a/pubsub/pubsub_test.go b/pubsub/pubsub_test.go index 0ec1a894f1..3c42442c68 100644 --- a/pubsub/pubsub_test.go +++ b/pubsub/pubsub_test.go @@ -78,7 +78,6 @@ func (s *driverSub) ReceiveBatch(ctx context.Context, maxMessages int) ([]*drive } case <-ctx.Done(): return nil, ctx.Err() - default: } } } diff --git a/pubsub/rabbitpubsub/amqp.go b/pubsub/rabbitpubsub/amqp.go index 503509602b..384a6b5725 100644 --- a/pubsub/rabbitpubsub/amqp.go +++ b/pubsub/rabbitpubsub/amqp.go @@ -18,6 +18,8 @@ package rabbitpubsub // Fake implementations of the interfaces are in fake_test.go import ( + "context" + amqp "github.com/rabbitmq/amqp091-go" ) @@ -46,6 +48,7 @@ type amqpConnection interface { // See https://pkg.go.dev/github.com/rabbitmq/amqp091-go#Channel for the documentation of these methods. type amqpChannel interface { Publish(exchange, routingKey string, msg amqp.Publishing) error + PublishWithContext(ctx context.Context, exchange, routingKey string, msg amqp.Publishing) error Consume(queue, consumer string) (<-chan amqp.Delivery, error) Ack(tag uint64) error Nack(tag uint64) error @@ -90,7 +93,11 @@ type channel struct { } func (ch *channel) Publish(exchange, routingKey string, msg amqp.Publishing) error { - return ch.ch.Publish(exchange, routingKey, mandatory, immediate, msg) + return ch.PublishWithContext(context.Background(), exchange, routingKey, msg) +} + +func (ch *channel) PublishWithContext(ctx context.Context, exchange, routingKey string, msg amqp.Publishing) error { + return ch.ch.PublishWithContext(ctx, exchange, routingKey, mandatory, immediate, msg) } func (ch *channel) Consume(queue, consumer string) (<-chan amqp.Delivery, error) { diff --git a/pubsub/rabbitpubsub/fake_test.go b/pubsub/rabbitpubsub/fake_test.go index 7a4d7dc501..0e848328db 100644 --- a/pubsub/rabbitpubsub/fake_test.go +++ b/pubsub/rabbitpubsub/fake_test.go @@ -153,6 +153,13 @@ func (ch *fakeChannel) QueueDeclareAndBind(queueName, exchangeName string) error } func (ch *fakeChannel) Publish(exchangeName, routingKey string, pub amqp.Publishing) error { + return ch.PublishWithContext(context.Background(), exchangeName, routingKey, pub) +} + +func (ch *fakeChannel) PublishWithContext(ctx context.Context, + exchangeName, routingKey string, + pub amqp.Publishing, +) error { if ch.isClosed() { return amqp.ErrClosed } diff --git a/runtimevar/blobvar/blobvar_test.go b/runtimevar/blobvar/blobvar_test.go index ba7e98c14d..4f6c7bf08c 100644 --- a/runtimevar/blobvar/blobvar_test.go +++ b/runtimevar/blobvar/blobvar_test.go @@ -17,10 +17,8 @@ package blobvar import ( "context" "errors" - "io/ioutil" "net/url" "os" - "path" "path/filepath" "strings" "testing" @@ -39,14 +37,15 @@ type harness struct { } func newHarness(t *testing.T) (drivertest.Harness, error) { - dir := path.Join(os.TempDir(), "go-cloud-blobvar") - if err := os.MkdirAll(dir, os.ModePerm); err != nil { - return nil, err - } + t.Helper() + + dir := t.TempDir() + b, err := fileblob.OpenBucket(dir, nil) if err != nil { return nil, err } + return &harness{dir: dir, bucket: b}, nil } @@ -96,17 +95,14 @@ func (verifyAs) ErrorCheck(v *runtimevar.Variable, err error) error { } func TestOpenVariable(t *testing.T) { - dir, err := ioutil.TempDir("", "gcdk-blob-var-example") - if err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(filepath.Join(dir, "myvar.json"), []byte(`{"Foo": "Bar"}`), 0666); err != nil { + dir := t.TempDir() + + if err := os.WriteFile(filepath.Join(dir, "myvar.json"), []byte(`{"Foo": "Bar"}`), 0666); err != nil { t.Fatal(err) } - if err := ioutil.WriteFile(filepath.Join(dir, "myvar.txt"), []byte("hello world!"), 0666); err != nil { + if err := os.WriteFile(filepath.Join(dir, "myvar.txt"), []byte("hello world!"), 0666); err != nil { t.Fatal(err) } - defer os.RemoveAll(dir) // Convert dir to a URL path, adding a leading "/" if needed on Windows // (on Unix, dirpath already has a leading "/"). diff --git a/runtimevar/filevar/example_test.go b/runtimevar/filevar/example_test.go index 5e93e966d1..521330ac58 100644 --- a/runtimevar/filevar/example_test.go +++ b/runtimevar/filevar/example_test.go @@ -17,8 +17,8 @@ package filevar_test import ( "context" "fmt" - "io/ioutil" "log" + "os" "gocloud.dev/runtimevar" "gocloud.dev/runtimevar/filevar" @@ -26,7 +26,7 @@ import ( func ExampleOpenVariable() { // Create a temporary file to hold our config. - f, err := ioutil.TempFile("", "") + f, err := os.CreateTemp("", "") if err != nil { log.Fatal(err) } diff --git a/runtimevar/filevar/filevar.go b/runtimevar/filevar/filevar.go index a51de89749..e9b5a38f84 100644 --- a/runtimevar/filevar/filevar.go +++ b/runtimevar/filevar/filevar.go @@ -44,7 +44,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "net/url" "os" "path/filepath" @@ -280,7 +279,7 @@ func (w *watcher) watch(ctx context.Context, notifier *fsnotify.Watcher, file st } // Read the file. - b, err := ioutil.ReadFile(file) + b, err := os.ReadFile(file) if err != nil { // File probably does not exist. Try again later. cur = w.updateState(&state{err: &errNotExist{err}}, cur) diff --git a/runtimevar/filevar/filevar_test.go b/runtimevar/filevar/filevar_test.go index 7f57fd0baa..e772f0ee6f 100644 --- a/runtimevar/filevar/filevar_test.go +++ b/runtimevar/filevar/filevar_test.go @@ -17,7 +17,6 @@ package filevar import ( "context" "errors" - "io/ioutil" "net/url" "os" "path/filepath" @@ -39,10 +38,10 @@ type harness struct { } func newHarness(t *testing.T) (drivertest.Harness, error) { - dir, err := ioutil.TempDir("", "filevar_test-") - if err != nil { - return nil, err - } + t.Helper() + + dir := t.TempDir() + return &harness{ dir: dir, closer: func() { _ = os.RemoveAll(dir) }, @@ -58,7 +57,7 @@ func (h *harness) MakeWatcher(ctx context.Context, name string, decoder *runtime func (h *harness) CreateVariable(ctx context.Context, name string, val []byte) error { // Write to a temporary file and rename; otherwise, // Watch can read an empty file during the write. - tmp, err := ioutil.TempFile(h.dir, "tmp") + tmp, err := os.CreateTemp(h.dir, "tmp") if err != nil { return err } @@ -114,10 +113,7 @@ func (verifyAs) ErrorCheck(v *runtimevar.Variable, err error) error { // Filevar-specific tests. func TestOpenVariable(t *testing.T) { - dir, err := ioutil.TempDir("", "filevar_test-") - if err != nil { - t.Fatal(err) - } + dir := t.TempDir() tests := []struct { description string @@ -177,18 +173,14 @@ func TestOpenVariable(t *testing.T) { } func TestOpenVariableURL(t *testing.T) { - dir, err := ioutil.TempDir("", "gcdk-filevar-example") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dir) + dir := t.TempDir() jsonPath := filepath.Join(dir, "myvar.json") - if err := ioutil.WriteFile(jsonPath, []byte(`{"Foo": "Bar"}`), 0666); err != nil { + if err := os.WriteFile(jsonPath, []byte(`{"Foo": "Bar"}`), 0666); err != nil { t.Fatal(err) } txtPath := filepath.Join(dir, "myvar.txt") - if err := ioutil.WriteFile(txtPath, []byte("hello world!"), 0666); err != nil { + if err := os.WriteFile(txtPath, []byte("hello world!"), 0666); err != nil { t.Fatal(err) } nonexistentPath := filepath.Join(dir, "filenotfound") @@ -292,7 +284,7 @@ func setupTestSecrets(ctx context.Context, dir, secretsPath string) (func(), err if err != nil { return cleanup, err } - if err := ioutil.WriteFile(secretsPath, sc, 0666); err != nil { + if err := os.WriteFile(secretsPath, sc, 0666); err != nil { return cleanup, err } return cleanup, nil diff --git a/runtimevar/httpvar/httpvar.go b/runtimevar/httpvar/httpvar.go index 096dd927fb..0c34bef374 100644 --- a/runtimevar/httpvar/httpvar.go +++ b/runtimevar/httpvar/httpvar.go @@ -36,7 +36,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "os" @@ -234,7 +234,7 @@ func (w *watcher) WatchVariable(ctx context.Context, prev driver.State) (driver. return errorState(err, prev), w.wait } - respBodyBytes, err := ioutil.ReadAll(resp.Body) + respBodyBytes, err := io.ReadAll(resp.Body) if err != nil { return errorState(err, prev), w.wait } diff --git a/runtimevar/runtimevar_test.go b/runtimevar/runtimevar_test.go index 7b1a27f775..6b57cda152 100644 --- a/runtimevar/runtimevar_test.go +++ b/runtimevar/runtimevar_test.go @@ -310,17 +310,15 @@ func TestVariable_Latest(t *testing.T) { wg.Add(numGoroutines) for i := 0; i < numGoroutines; i++ { go func() { - for { - val, err := v.Latest(ctx) - if err != nil { - // Errors are unexpected at this point. - t.Error(err) - } else if val.Value != content2 { - t.Errorf("got %v want %s", val.Value, content2) - } - wg.Done() - return + val, err := v.Latest(ctx) + if err != nil { + // Errors are unexpected at this point. + t.Error(err) + } else if val.Value != content2 { + t.Errorf("got %v want %s", val.Value, content2) } + wg.Done() + return }() } wg.Wait() diff --git a/samples/guestbook/aws/provision_db/main.go b/samples/guestbook/aws/provision_db/main.go index 42377e62d2..45e2e1adac 100644 --- a/samples/guestbook/aws/provision_db/main.go +++ b/samples/guestbook/aws/provision_db/main.go @@ -20,7 +20,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "log" "net/http" "os" @@ -66,7 +65,7 @@ func provisionDb(dbHost, region, securityGroupID, dbName, dbPassword, schemaPath // Create a temporary directory to hold the certificates. // We resolve all symlinks to avoid Docker on Mac issues, see // https://github.com/google/go-cloud/issues/110. - tempdir, err := ioutil.TempDir("", "guestbook-ca") + tempdir, err := os.MkdirTemp("", "guestbook-ca") if err != nil { return fmt.Errorf("creating temp dir for certs: %v", err) } diff --git a/samples/guestbook/gcp/deploy/main.go b/samples/guestbook/gcp/deploy/main.go index 1a22393639..b6a0ae79f3 100644 --- a/samples/guestbook/gcp/deploy/main.go +++ b/samples/guestbook/gcp/deploy/main.go @@ -20,7 +20,6 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" "log" "os" "os/exec" @@ -68,7 +67,7 @@ func deploy(guestbookDir, tfStatePath string) error { if zone == "" { return fmt.Errorf("empty or missing cluster_zone in %s", tfStatePath) } - tempDir, err := ioutil.TempDir("", "guestbook-k8s-") + tempDir, err := os.MkdirTemp("", "guestbook-k8s-") if err != nil { return fmt.Errorf("making temp dir: %v", err) } @@ -77,7 +76,7 @@ func deploy(guestbookDir, tfStatePath string) error { // Fill in Kubernetes template parameters. proj := strings.Replace(tfState.Project.Value, ":", "/", -1) imageName := fmt.Sprintf("gcr.io/%s/guestbook", proj) - gbyin, err := ioutil.ReadFile(filepath.Join(guestbookDir, "gcp", "guestbook.yaml.in")) + gbyin, err := os.ReadFile(filepath.Join(guestbookDir, "gcp", "guestbook.yaml.in")) if err != nil { return fmt.Errorf("reading guestbook.yaml.in: %v", err) } @@ -93,7 +92,7 @@ func deploy(guestbookDir, tfStatePath string) error { for old, new := range replacements { gby = strings.Replace(gby, old, new, -1) } - if err := ioutil.WriteFile(filepath.Join(tempDir, "guestbook.yaml"), []byte(gby), 0666); err != nil { + if err := os.WriteFile(filepath.Join(tempDir, "guestbook.yaml"), []byte(gby), 0666); err != nil { return fmt.Errorf("writing guestbook.yaml: %v", err) } diff --git a/samples/guestbook/gcp/provision_db/main.go b/samples/guestbook/gcp/provision_db/main.go index 8673a93a2e..b224e656d4 100644 --- a/samples/guestbook/gcp/provision_db/main.go +++ b/samples/guestbook/gcp/provision_db/main.go @@ -20,7 +20,6 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" "log" "os" "os/exec" @@ -78,7 +77,7 @@ func provisionDB(projectID, serviceAccount, dbInstance, dbName, dbPassword, sche // Create a temporary directory to hold the service account key. // We resolve all symlinks to avoid Docker on Mac issues, see // https://github.com/google/go-cloud/issues/110. - serviceAccountVolDir, err := ioutil.TempDir("", "guestbook-service-acct") + serviceAccountVolDir, err := os.MkdirTemp("", "guestbook-service-acct") if err != nil { return fmt.Errorf("creating temp dir to hold service account key: %v", err) } @@ -93,7 +92,7 @@ func provisionDB(projectID, serviceAccount, dbInstance, dbName, dbPassword, sche if _, err := run(gcp.cmd("iam", "service-accounts", "keys", "create", "--iam-account="+serviceAccount, serviceAccountVolDir+"/key.json")...); err != nil { return fmt.Errorf("creating new service account key: %v", err) } - keyJSONb, err := ioutil.ReadFile(filepath.Join(serviceAccountVolDir, "key.json")) + keyJSONb, err := os.ReadFile(filepath.Join(serviceAccountVolDir, "key.json")) if err != nil { return fmt.Errorf("reading key.json file: %v", err) } diff --git a/samples/guestbook/localdb/main.go b/samples/guestbook/localdb/main.go index bd4caf3d33..ce89d1d10a 100644 --- a/samples/guestbook/localdb/main.go +++ b/samples/guestbook/localdb/main.go @@ -19,7 +19,6 @@ import ( "errors" "flag" "fmt" - "io/ioutil" "log" "os" "os/exec" @@ -95,11 +94,11 @@ func runLocalDB(containerName, guestbookDir string) error { } log.Printf("Initializing database schema and users") - schema, err := ioutil.ReadFile(filepath.Join(guestbookDir, "schema.sql")) + schema, err := os.ReadFile(filepath.Join(guestbookDir, "schema.sql")) if err != nil { return fmt.Errorf("reading schema: %v", err) } - roles, err := ioutil.ReadFile(filepath.Join(guestbookDir, "roles.sql")) + roles, err := os.ReadFile(filepath.Join(guestbookDir, "roles.sql")) if err != nil { return fmt.Errorf("reading roles: %v", err) } diff --git a/samples/order/frontend_test.go b/samples/order/frontend_test.go index 7803ff0667..f6d1cb51df 100644 --- a/samples/order/frontend_test.go +++ b/samples/order/frontend_test.go @@ -18,8 +18,8 @@ import ( "context" "fmt" "io" - "io/ioutil" "net/http/httptest" + "os" "strings" "testing" "time" @@ -43,11 +43,11 @@ func TestOrderForm(t *testing.T) { if res.StatusCode != 200 { t.Fatalf("got %d, want 200", res.StatusCode) } - wantb, err := ioutil.ReadFile("order-form.htmlt") + wantb, err := os.ReadFile("order-form.htmlt") if err != nil { t.Fatal(err) } - gotb, err := ioutil.ReadAll(res.Body) + gotb, err := io.ReadAll(res.Body) if err != nil { t.Fatal(err) } @@ -80,7 +80,7 @@ func TestCreateOrder(t *testing.T) { t.Fatal(err) } defer r.Close() - gotb, err := ioutil.ReadAll(r) + gotb, err := io.ReadAll(r) if err != nil { t.Fatal(err) } @@ -126,7 +126,7 @@ func TestListOrders(t *testing.T) { if res.StatusCode != 200 { t.Fatalf("got %d, want 200", res.StatusCode) } - gotb, err := ioutil.ReadAll(res.Body) + gotb, err := io.ReadAll(res.Body) if err != nil { t.Fatal(err) } diff --git a/samples/order/order.go b/samples/order/order.go index ec608ed0d3..075f4580ad 100644 --- a/samples/order/order.go +++ b/samples/order/order.go @@ -28,7 +28,6 @@ package main import ( "context" "flag" - "io/ioutil" "log" "os" "path/filepath" @@ -128,7 +127,7 @@ func setup(conf config) (_ *frontend, _ *processor, cleanup func(), err error) { burl := conf.bucketURL if burl == "" { - dir, err := ioutil.TempDir("", "gocdk-order") + dir, err := os.MkdirTemp("", "gocdk-order") if err != nil { return nil, nil, cleanup, err } diff --git a/samples/order/processor.go b/samples/order/processor.go index 93754149f8..acd34b313e 100644 --- a/samples/order/processor.go +++ b/samples/order/processor.go @@ -55,7 +55,6 @@ func (p *processor) run(ctx context.Context) error { return err } } - return nil } // handleRequest handles one image-processing request. diff --git a/samples/tutorial/main.go b/samples/tutorial/main.go index fc6357d64f..1faac20541 100644 --- a/samples/tutorial/main.go +++ b/samples/tutorial/main.go @@ -17,7 +17,6 @@ package main import ( "context" - "io/ioutil" "log" "os" @@ -46,7 +45,7 @@ func main() { defer b.Close() // Prepare the file for upload. - data, err := ioutil.ReadFile(file) + data, err := os.ReadFile(file) if err != nil { log.Fatalf("Failed to read file: %s", err) } diff --git a/server/requestlog/stackdriver_test.go b/server/requestlog/stackdriver_test.go index 50b2e1dc0e..2b6d7b98e4 100644 --- a/server/requestlog/stackdriver_test.go +++ b/server/requestlog/stackdriver_test.go @@ -20,7 +20,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/http/httptest" "strings" @@ -179,7 +178,7 @@ func BenchmarkStackdriverLog(b *testing.B) { buf.Reset() b.ResetTimer() - l = NewStackdriverLogger(ioutil.Discard, func(error) {}) + l = NewStackdriverLogger(io.Discard, func(error) {}) for i := 0; i < b.N; i++ { l.Log(ent) } @@ -195,7 +194,7 @@ func BenchmarkE2E(b *testing.B) { if err != nil { b.Fatal(err) } - io.Copy(ioutil.Discard, resp.Body) + io.Copy(io.Discard, resp.Body) resp.Body.Close() } } @@ -203,7 +202,7 @@ func BenchmarkE2E(b *testing.B) { run(b, http.HandlerFunc(benchHandler)) }) b.Run("WithLog", func(b *testing.B) { - l := NewStackdriverLogger(ioutil.Discard, func(error) {}) + l := NewStackdriverLogger(io.Discard, func(error) {}) run(b, NewHandler(l, http.HandlerFunc(benchHandler))) }) }