src/archive/tar/example_test.go GO 72 lines View on github.com → Search inside
1// Copyright 2013 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.45package tar_test67import (8	"archive/tar"9	"bytes"10	"fmt"11	"io"12	"log"13	"os"14)1516func Example_minimal() {17	// Create and add some files to the archive.18	var buf bytes.Buffer19	tw := tar.NewWriter(&buf)20	var files = []struct {21		Name, Body string22	}{23		{"readme.txt", "This archive contains some text files."},24		{"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},25		{"todo.txt", "Get animal handling license."},26	}27	for _, file := range files {28		hdr := &tar.Header{29			Name: file.Name,30			Mode: 0600,31			Size: int64(len(file.Body)),32		}33		if err := tw.WriteHeader(hdr); err != nil {34			log.Fatal(err)35		}36		if _, err := tw.Write([]byte(file.Body)); err != nil {37			log.Fatal(err)38		}39	}40	if err := tw.Close(); err != nil {41		log.Fatal(err)42	}4344	// Open and iterate through the files in the archive.45	tr := tar.NewReader(&buf)46	for {47		hdr, err := tr.Next()48		if err == io.EOF {49			break // End of archive50		}51		if err != nil {52			log.Fatal(err)53		}54		fmt.Printf("Contents of %s:\n", hdr.Name)55		if _, err := io.Copy(os.Stdout, tr); err != nil {56			log.Fatal(err)57		}58		fmt.Println()59	}6061	// Output:62	// Contents of readme.txt:63	// This archive contains some text files.64	// Contents of gopher.txt:65	// Gopher names:66	// George67	// Geoffrey68	// Gonzo69	// Contents of todo.txt:70	// Get animal handling license.71}

Code quality findings 3

String to byte slice conversion inside loop allocates a new slice each iteration; convert once before the loop
info correctness string-to-byte-in-loop
if _, err := tw.Write([]byte(file.Body)); err != nil {
Formatted output to console; prefer structured logging for consistency
info correctness fmt-printf
fmt.Printf("Contents of %s:\n", hdr.Name)
Unstructured output; use a structured logging library (e.g., slog, zap, zerolog, logrus)
info correctness fmt-println
fmt.Println()

Security findings 1

Potential decompression bomb vulnerability if input is untrusted, ensure to limit the number of bytes read
security decompression-bomb
tr := tar.NewReader(&buf)

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.