A Read–Eval–Print Loop (REPL) is one of the most ubiquitous—and under-appreciated—command-line interfaces in use today. From the Python REPL and Node.js console, to IRB for Ruby, or even the MySQL CLI, REPLs let you carry forward state and context within a lightweight, shell-like session. What’s astonishing is how little code it takes to build one yourself. Below is a minimal starting point for a REPL in Go that you can extend however you like.
This fully compilable REPL program supports two keyword commands, help and exit, while echoing all other input back to the console.
// repl.go
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
const helpText = `Simple REPL Help:
• Type anything and I'll echo it back.
• Type "help" to show this message.
• Type "exit" or "quit" to leave.
`
func main() {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("> ")
line, err := reader.ReadString('\n')
if err != nil {
fmt.Fprintln(os.Stderr, "Error reading input:", err)
break
}
input := strings.TrimSpace(line)
if input == "" {
continue
}
switch input {
case "exit", "quit":
fmt.Println("Goodbye!")
return
case "help":
fmt.Print(helpText)
continue
}
// default echo behavior
fmt.Println("You typed:", input)
}
}
Once compiled and run in BASH it looks like:
./brepl
> help
Simple REPL Help:
• Type anything and I'll echo it back.
• Type "help" to show this message.
• Type "exit" or "quit" to leave.
> Hello, world!
You typed: Hello, world!
> What if I type exit?
You typed: What if I type exit?
> exit
Goodbye!
This is a great starting point for implementing a few commands. Combine this with the functions in another CLI on this site (e.g. iptool) to add real functionality. And, replace the “case” statements with the Cobra CLI package and manageably add dozens of command and simplify help while you are at it! Have fun!