How to remove special char in golang while reading a file?

I have a file like this: Each line represents a website

1 www.google.com$
2 www.apple.com$
3 www.facebook.com$

I read it in golang like this:

type ListConf struct {
    File  string
    Datas map[string]struct{}
}

func loadListConf(conf *ListConf, path string) {
    file, err := os.Open(path + "/" + conf.File)
    if err != nil {
        fmt.Println("Load conf " + conf.File + " error: " + err.Error())
        return
    }
    defer file.Close()
    conf.Datas = make(map[string]struct{})
    buf := bufio.NewReader(file)
    end := false
    for !end {
        line, err := buf.ReadString('\n')
        if err != nil {
            if err != io.EOF {
                fmt.Println("Load conf " + conf.File + " error: " + err.Error())
                return
            } else {
                end = true
            }
        }
        item := strings.Trim(line, "\n")
        if item == "" {
            continue
        }
        conf.Datas[item] = struct{}{}
    }
}

But when I find a key that looks like "www.google.com" on the map, it shows that there is no "www.google.com" on the map.

website := "www.google.com"
if _, ok := conf.Datas[website]; ok {
    fmt.Printf("%s is in the map.", website)
} else {
    fmt.Printf("%s is not in the map.", website)
}

It prints "www.google.com is not on the map." I found that a ^ M at the end of each key on the map, my question is, how can I remove the ^ M character?

www.google.com^M
www.apple.com^M
www.facebook.com^M
+4
source share
2 answers

The default separator lines in text files in Windows is a sequence of two characters: \r\n. ^MThat you see in their lines \r.

bufio.Scanner :

scanner := bufio.NewScanner(file)
for scanner.Scan() {
    fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
    fmt.Fprintln(os.Stderr, "error reading from the file:", err)
}
+4

, ...

\r

line, err := buf.ReadString('\n') line = strings.TrimRight(line, "\r")

\r (^ M) , .

+2

Source: https://habr.com/ru/post/1626807/


All Articles