gostdoutpager

Paging output from Go


I'm trying print to stdout from golang using $PAGER or manually invoking more or less to allow the user to easily scroll through a lot of options. How can I achieve this?


Solution

  • You can use the os/exec package to start a process that runs less (or whatever is in $PAGER) and then pipe a string to its standard input. The following worked for me:

    func main() {
        // Could read $PAGER rather than hardcoding the path.
        cmd := exec.Command("/usr/bin/less")
    
        // Feed it with the string you want to display.
        cmd.Stdin = strings.NewReader("The text you want to show.")
    
        // This is crucial - otherwise it will write to a null device.
        cmd.Stdout = os.Stdout
    
        // Fork off a process and wait for it to terminate.
        err := cmd.Run()
        if err != nil {
            log.Fatal(err)
        }
    }