Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - How increase maximum Stdin input length?

Tags:

go

What's the recommended way to allow more than 1024 characters when reading from standard input in Go?

For example, this code using bufio.Scanner has a maximum input length of 1024.

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    input := scanner.Text()
    fmt.Println(input)
}

Update after some suggested answers... Sorry guys - I must still be doing something wrong, or misstated the question. I tried both suggestions and still see the same issue. Below is an updated version of the code. The symptom is that the scanner won't accept input after the 1024th character. e.g. Try to run this then paste in a string that's 1025 characters long, and it'll stop accepting input after character 1024.

package main

import (
    "bufio"
    "bytes"
    "fmt"
    "log"
    "os"
)

func main() {
    var buffer bytes.Buffer
    scanner := bufio.NewScanner(os.Stdin)

    for {
        done := scanner.Scan()
        buffer.WriteString(scanner.Text())
        if done == true {
            if scanner.Err() != nil {
                log.Fatal("Error scanning input")
            }
            break
        }
    }
    fmt.Println(buffer.String())
}
like image 404
Dan Tanner Avatar asked Sep 01 '25 17:09

Dan Tanner


1 Answers

You are ignoring the return value of scanner.Scan() which is a bool indicating whether you have reached the end.

Specifically:

It returns false when the scan stops, either by reaching the end of the input or an error. After Scan returns false, the Err method will return any error that occurred during scanning, except that if it was io.EOF, Err will return nil.

So you need to continue running scanner.Scan() in a loop, until it returns false, then check .Err() to ensure you didn't stop scanning because of a non-EOF error.

like image 197
sberry Avatar answered Sep 04 '25 09:09

sberry