Documentation
¶
Overview ¶
Package utfbom implements the detection of the BOM (Unicode Byte Order Mark) and removing as necessary. It wraps an io.Reader object, creating another object (Reader) that also implements the io.Reader interface but provides automatic BOM checking and removing as necessary.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Skip ¶
Skip returns a Reader that reads from rd without its leading BOM (Unicode Byte Order Mark), and the encoding indicated by that BOM, or Unknown if no supported BOM was detected.
Skip reads up to 4 bytes from rd before it returns, so it may block. An error that occurs while reading them is not returned by Skip: the returned Reader's Read returns it once, after the bytes that remain after BOM removal.
If rd is already a *Reader, Skip returns rd itself and the encoding it detected, without reading from it. Use SkipOnly if the encoding is not needed.
Example ¶
package main
import (
"fmt"
"io"
"strings"
"github.com/dimchansky/utfbom"
)
func main() {
r, enc := utfbom.Skip(strings.NewReader("\xEF\xBB\xBFhello"))
data, err := io.ReadAll(r)
if err != nil {
panic(err)
}
fmt.Printf("%s %q\n", enc, data)
}
Output: UTF8 "hello"
Example (Utf16) ¶
The BOM is removed, but the remaining bytes stay UTF-16: nothing is transcoded.
package main
import (
"fmt"
"io"
"strings"
"github.com/dimchansky/utfbom"
)
func main() {
r, enc := utfbom.Skip(strings.NewReader("\xFF\xFEh\x00i\x00"))
data, err := io.ReadAll(r)
if err != nil {
panic(err)
}
fmt.Printf("%s % X\n", enc, data)
}
Output: UTF16LittleEndian 68 00 69 00
Types ¶
type Encoding ¶
type Encoding int
Encoding is a UTF encoding identified by a BOM.
const ( // Unknown encoding, returned when no BOM was detected Unknown Encoding = iota // UTF8, BOM bytes: EF BB BF UTF8 // UTF-16, big-endian, BOM bytes: FE FF UTF16BigEndian // UTF-16, little-endian, BOM bytes: FF FE UTF16LittleEndian // UTF-32, big-endian, BOM bytes: 00 00 FE FF UTF32BigEndian // UTF-32, little-endian, BOM bytes: FF FE 00 00 UTF32LittleEndian )
Constants to identify detected UTF encodings.
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader is an io.Reader that returns the bytes of the underlying reader without the leading BOM (Unicode Byte Order Mark). Create it with Skip or SkipOnly. Reader does not close the underlying reader.
func SkipOnly ¶
SkipOnly is like Skip but does not return the encoding. It also reads from rd immediately and may block, and an error from that read is returned later by Read.
Example ¶
package main
import (
"fmt"
"io"
"strings"
"github.com/dimchansky/utfbom"
)
func main() {
data, err := io.ReadAll(utfbom.SkipOnly(strings.NewReader("\xEF\xBB\xBFhello")))
if err != nil {
panic(err)
}
fmt.Printf("%q\n", data)
}
Output: "hello"