forked from exercism/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
51 lines (43 loc) · 1.19 KB
/
api.go
File metadata and controls
51 lines (43 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package api
import (
"bytes"
"io/ioutil"
"golang.org/x/net/html/charset"
"golang.org/x/text/transform"
)
const (
mimeType = "text/plain"
)
var (
utf8BOM = []byte{0xef, 0xbb, 0xbf}
)
func readFileAsUTF8String(filename string) (*string, error) {
b, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
encoding, _, certain := charset.DetermineEncoding(b, mimeType)
if !certain {
// We don't want to use an uncertain encoding.
// In particular, doing that may mangle UTF-8 files
// that have only ASCII in their first 1024 bytes.
// See https://github.com/exercism/cli/issues/309.
// So if we're unsure, use UTF-8 (no transformation).
s := string(b)
return &s, nil
}
decoder := encoding.NewDecoder()
decodedBytes, _, err := transform.Bytes(decoder, b)
if err != nil {
return nil, err
}
// Drop the UTF-8 BOM that may have been added. This isn't necessary, and
// it's going to be written into another UTF-8 buffer anyway once it's JSON
// serialized.
//
// The standard recommends omitting the BOM. See
// http://www.unicode.org/versions/Unicode5.0.0/ch02.pdf
decodedBytes = bytes.TrimPrefix(decodedBytes, utf8BOM)
s := string(decodedBytes)
return &s, nil
}