如何读取文件,如果它不是有效的UTF-8,则错误中止?

In Go, I want to read in a file line by line, into str's or []rune's.

The file should be encoded in UTF-8, but my program shouldn't trust it. If it contains invalid UTF-8, I want to properly handle the error.

There is bytes.Runes(s []byte) []rune, but that has no error return value. Will it panic on encountering invalid UTF-8?

For example,

package main

import (
    "bufio"
    "fmt"
    "io/ioutil"
    "os"
    "strings"
    "unicode/utf8"
)

func main() {
    tFile := "text.txt"
    t := []byte{'\xFF', '
'}
    ioutil.WriteFile(tFile, t, 0666)
    f, err := os.Open(tFile)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    defer f.Close()
    r := bufio.NewReader(f)
    s, err := r.ReadString('
')
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    s = strings.TrimRight(s, "
")
    fmt.Println(t, s, []byte(s))
    if !utf8.ValidString(s) {
        fmt.Println("!utf8.ValidString")
    }
}

Output:

[255 10] � [255]
!utf8.ValidString

For example:

import (
    "io/ioutil"
    "log"
    "unicode/utf8"
)

// ...

buf, err := ioutil.ReadAll(fname)
if error != nil {
        log.Fatal(err)
}

size := 0
for start := 0; start < len(buf); start += size {
        var r rune
        if r, size = utf8.DecodeRune(buf[start:]); r == utf8.RuneError {
                log.Fatalf("invalid utf8 encoding at ofs %d", start)
        }
}

utf8.DecodeRune godocs:

DecodeRune unpacks the first UTF-8 encoding in p and returns the rune and its width in bytes. If the encoding is invalid, it returns (RuneError, 1), an impossible result for correct UTF-8.