1

I am learning Go these days and I am trying to read a file which includes a list of URLs so that I can send a simple GET request to them. So, I need to read the list and then add its line of the list as an element in a slice. However, I am getting a weird output. Below are my code and the .txt file.

code:

func openFile() {
    urls := make([]string, 3)
    for _, filename := range os.Args[1:] {
        urlsBytes, err := ioutil.ReadFile(filename)

        if err != nil {
            fmt.Println(err)
        }

        for _, line := range strings.Split(string(urlsBytes), "\n") {
            urls = append(urls, line)

        }

    }
    fmt.Println(urls)

}

file:

https://www.youtube.com/
https://www.facebook.com/
https://aws.amazon.com/

output:

go run Main.go test2.txt
 https://aws.amazon.com/]/m/
John
  • 13
  • 1
  • 4

1 Answers1

4

You can use bufio.Scanner for easy reading of data such as a file of newline character delimited text.

file, err := os.Open("lines.txt")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

sc := bufio.NewScanner(file)
lines := make([]string, 0)

// Read through 'tokens' until an EOF is encountered.
for sc.Scan() {
    lines = append(lines, sc.Text())
}

if err := sc.Err(); err != nil {
    log.Fatal(err)
}

This also works well with other streams on delimited text since bufio.NewScanner accepts a io.Reader.

Jay
  • 1,089
  • 12
  • 29