2

I'm trying to write a golang program to control mpv via issuing commands to a unix socket running at /tmp/mpvsocket.

This is what I've tried so far:

func main() {                                     
  c, err := net.Dial("unix", "/tmp/mpvsocket")    
  if err != nil {                                 
    panic(err)                                    
  }                                               
  defer c.Close()                                 

  _, err = c.Write([]byte(`{"command":["quit"]}`))
  if err != nil {                                 
    log.Fatal("write error:", err)                
  }                                               
}                                                 

This should cause mpv to quit but nothing happens.

This command can be issued via the command line to get the expected results:

echo '{ "command": ["quit"] }' | socat - /tmp/mpvsocket

It uses socat to send the JSON to the socket. How can I send this to the socket using Golang?

2
  • 2
    I'm not sure if this is the issue, but there is one difference between those two methods: echo sends a newline and your Go program doesn't. Commented Jan 21, 2017 at 19:51
  • @AndySchweig Yep that was it!
    – hermancain
    Commented Jan 21, 2017 at 20:18

1 Answer 1

1

Thanks to @AndySchweig in the comments above, I needed a new line after my JSON.

The fixed line:

  _, err = c.Write([]byte(`{"command":["quit"]}` + "\n"))

The full block of fixed code:

func main() {                                     
  c, err := net.Dial("unix", "/tmp/mpvsocket")    
  if err != nil {                                 
    panic(err)                                    
  }                                               
  defer c.Close()                                 

  _, err = c.Write([]byte(`{"command":["quit"]}` + "\n"))
  if err != nil {                                 
    log.Fatal("write error:", err)                
  }                                               
}                                     
1
  • 1
    Also, check the bytes written b, err = c.Write(... to make sure that the whole string was sent.
    – Xeoncross
    Commented Jan 21, 2017 at 21:15

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.