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/
0

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.