Golang: Read First n Bytes of File

By Xah Lee. Date: .
package main

import "fmt"
import "os"

// open file. read first 200 bytes. print it as string

// getHeadBytes gets the first n bytes of a file
func getHeadBytes(path string, n int) []byte {

	xfile, err := os.Open(path) // For read access.

	if err != nil {
		panic(err)
	}

	defer xfile.Close()

	xheadBytes := make([]byte, n)
	m, err := xfile.Read(xheadBytes)
	if err != nil {
		panic(err)
	}

	return xheadBytes[:m]
}

func main() {

	var xfilePath = "/Users/xah/web/xahlee_info/golang/golang_read_file.html"

	fmt.Printf("%v\n", string(getHeadBytes(xfilePath, 200)))

}

Golang: Read File