Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write on thermal printer device in golang

I have a thermal printer(ESC/POS) already configured on my linux machine and using the terminal command (as root) I can make it print:

echo "Hello!" > /dev/usb/lp0

However, doing the same procedure in golang nothing happens:

package main

import (
    "fmt"
    "os"
)

func main() {
   fmt.Println("Hello Would!")

   f, err := os.Open("/dev/usb/lp0")

   if err != nil {
       panic(err)
   }

   defer f.Close()

   f.Write([]byte("Hello world!"))
}

What am I doing wrong?

like image 555
Augusto Pimenta Avatar asked Sep 15 '25 16:09

Augusto Pimenta


1 Answers

As described in the documentation os.Open() opens a file read-only.

You would have discovered the problem if you had checked the return from your Write() call. Always check errors. Don't ignore them, even in tiny programs like this; they will give you a clue as to what is wrong.

To fix the problem, open the device special for writing with os.OpenFile().

f, err := os.OpenFile("/dev/usb/lp0", os.O_RDWR, 0)
like image 130
Michael Hampton Avatar answered Sep 18 '25 06:09

Michael Hampton