Using fmt.Println for error handling isnt a practical way, especially in linux or unix based systems.
because if you're using bash or zsh or any other shell, there will be 3 types of file descriptors, stdout, stderr, and stdin (which are low level integer table numbers that the kernel assign them for each communication channel )
when logging erros with fmt.Println you're polluting your Standard output data stream ( stdout ( 1 ) ) which might be used for CLI driven utility or similar, and using print() or println() isnt ideal for production grade, because both of them redirect every output to stderr amd both are almost temporary built in functions for fast debugging/bootstrapping that might get removed
Here is the show case :
package main
import "fmt"
func main() {
println("Directed to stderr")
fmt.Println("Directed to stdout")
}
When compiling and running as an executable :
[lost learning]$ ./main # Default case
Directed to stderr
Directed to stdout
[lost learning]$ ./main 2>/dev/null # Redirecting the Standard Error to null
Directed to stdout
[lost learning]$ ./main 1>/dev/null # Redirecting the Standard Output to null
Directed to stderr
[lost learning]$ ./main > output # Redirection operator ">" takes only the stdout
Directed to stderr
[lost learning]$ cat output
Directed to stdout
[lost learning]$ ./main 2>&1 | tee output2 # We can merge a stream to another stream
[lost learning]$ cat output2
Directed to stderr
Directed to stdout
[lost learning]$
Better approach using fmt.Fprintln() and lib os for writing string into stdout or stderr or even stdin, without relying on built in debug functions :
package main
import (
"fmt"
"os"
)
func main() {
fmt.Fprintln(os.Stderr, "Directed to stderr")
fmt.Fprintln(os.Stdout, "Directed to stdout")
}
Output :
[lost learning]$ ./main # Default
Directed to stderr
Directed to stdout
[lost learning]$ ./main > output
[lost learning]$ cat output # Clean output
Directed to stdout
[lost learning]$ ./main > output 2>&1 # Merge stream 2 to 1
[lost learning]$ cat output
Directed to stderr
Directed to stdout
And i have to mention that there is a better way for debugging and error handling that its pretty recomended especially if you're building a production grade backend, by using libs like log, slog, errors, Errorf ...
so this writeup is only if you don't want to not external libs .
Top comments (0)