从标准输出中删除一个内存地址在Golang中的操作。

huangapple go评论84阅读模式
英文:

Removing a memory address from standard output in Golang

问题

我正在尝试用Go语言创建一个git的克隆版本。我对Go语言特别是"os"和"io"包还不太熟悉。

问题:为什么我的函数在输出的开头返回一个内存地址(或者可能是读取的字节数?)?有没有办法将其从输出中删除,以便我得到预期的输出?

预期输出:dumpty vanilla dooby humpty donkey yikes

实际输出:blob 40\x00dumpty vanilla dooby humpty donkey yikes

命令:./my_git.sh cat-file -p <HASH>

相关代码:

if os.Args[2] == "-p" {
    // 声明SHA
    sha := os.Args[3]

    // 将SHA转换为可读的文件路径
    folder := string(sha[0:2])
    blob := string(sha[2:])
    filePath := ".git/objects/" + folder + "/" + blob

    file, err := os.Open(filePath)
    if err != nil {
        log.Fatal(err)
    }

    r, readError := zlib.NewReader(file)
    if readError != nil {
        log.Fatal(readError)
    }

    io.Copy(os.Stdout, r)
    r.Close()
}
英文:

I am attempting to create a clone of git in Go. I am new to Go, especially the "os" and "io" packages.

Question: Why is my function returning a memory address (or maybe it's the number of bytes read?) at the beginning of my output? Is there a way to remove it from the output so that I get the expected output?

Expected output: dumpty vanilla dooby humpty donkey yikes

Got: blob 40\x00dumpty vanilla dooby humpty donkey yikes

Command: ./my_git.sh cat-file -p &lt;HASH&gt;

Relevant Code:

if os.Args[2] == &quot;-p&quot; {
			// Declare SHA
			sha := os.Args[3]

			// Convert SHA to readable file path
			folder := string(sha[0:2])
			blob := string(sha[2:])
			filePath := &quot;.git/objects/&quot; + folder + &quot;/&quot; + blob

			file, err := os.Open(filePath)
			if err != nil {
				log.Fatal(err)
			}

			r, readError := zlib.NewReader(file)
			if readError != nil {
				log.Fatal(readError)
			}

			io.Copy(os.Stdout, r)
			r.Close()
		}

答案1

得分: 1

blob 40\x00 是文件内容(解压缩后)的一部分。它是对象头部分:

  • 对象的类型(这里是 "blob";其他类型包括 "commit" 和 "tree")
  • 对象的大小(这里是40字节)
  • 以及一个空字节

你不能简单地删除它。你必须理解头部才能理解对象内容的含义。

请参阅《Git Internals - Git Objects》一章,了解更多信息。

英文:

blob 40\x00 is literally part of the (decompressed) file content. It is the object header:

  • the type of the object (here "blob"; other types include "commit" and "tree", for instance)
  • the object's size in bytes (here 40)
  • and a null byte

You can't just remove that. You have to understand the header to make sense of the object content proper.

See the "Git Internals - Git Objects" chapter of the git book for further information.

huangapple
  • 本文由 发表于 2022年2月9日 07:09:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/71042059.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定