How to correctly output a string in a windows console with go?

I have exein go that prints utf-8 lines with special characters in it.
Since this exe is used for use in the console window, its output is distorted because Windows uses the ibm850encoding (aka code page 850).

How would you make sure that go exeprints correctly encoded lines for console windows, i.e. print, for example:

éèïöîôùòèìë

instead (without translation on the right charset )

├®├¿├»├Â├«├┤├╣├▓├¿├¼├½
+5
source share
4 answers

- " Go" ( CC BY- NC-SA 3.0) ( ), Jan Newmarch . .

(, ), go-charset ( ).
utf-8 ibm850 , DOS:

éèïöîôùòèìë

:

package main

import (
    "bytes"
    "code.google.com/p/go-charset/charset"
    _ "code.google.com/p/go-charset/data"
    "fmt"
    "io"
    "log"
    "strings"
)

func translate(tr charset.Translator, in string) (string, error) {
    var buf bytes.Buffer
    r := charset.NewTranslatingReader(strings.NewReader(in), tr)
    _, err := io.Copy(&buf, r)
    if err != nil {
        return "", err
    }
    return string(buf.Bytes()), nil
}

func Utf2dos(in string) string {
    dosCharset := "ibm850"
    cs := charset.Info(dosCharset)
    if cs == nil {
        log.Fatal("no info found for %q", dosCharset)
    }
    fromtr, err := charset.TranslatorTo(dosCharset)
    if err != nil {
        log.Fatal("error making translator from %q: %v", dosCharset, err)
    }
    out, err := translate(fromtr, in)
    if err != nil {
        log.Fatal("error translating from %q: %v", dosCharset, err)
    }
    return out
}

func main() {
    test := "éèïöîôùòèìë"
    fmt.Println("utf-8:\n", test)
    fmt.Println("ibm850:\n", Utf2dos(test))
}
+3
// Alert: This is Windows-specific, uses undocumented methods, does not
// handle stdout redirection, does not check for errors, etc.
// Use at your own risk.
// Tested with Go 1.0.2-windows-amd64.

package main

import "unicode/utf16"
import "syscall"
import "unsafe"

var modkernel32 = syscall.NewLazyDLL("kernel32.dll")
var procWriteConsoleW = modkernel32.NewProc("WriteConsoleW")

func consolePrintString(strUtf8 string) {
    var strUtf16 []uint16
    var charsWritten *uint32

    strUtf16 = utf16.Encode([]rune(strUtf8))
    if len(strUtf16) < 1 {
        return
    }

    syscall.Syscall6(procWriteConsoleW.Addr(), 5,
        uintptr(syscall.Stdout),
        uintptr(unsafe.Pointer(&strUtf16[0])),
        uintptr(len(strUtf16)),
        uintptr(unsafe.Pointer(charsWritten)),
        uintptr(0),
        0)
}

func main() {
    consolePrintString("Hello ☺\n")
    consolePrintString("éèïöîôùòèìë\n")
}
+4

2016 (2017) golang.org/x/text, encoding charmap, ISO-8859, Windows 1252.

. " - "

r := charmap.ISO8859_1.NewDecoder().Reader(f)
io.Copy(out, r)

, ISO-8859-1 (my_isotext.txt), (my_utf.txt) .
ISO-8859-1 UTF-8 (f) .

0

All Articles