Search code examples
socketsgonetwork-programmingunix-socket

Send JSON to a unix socket with golang


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?


Solution

  • 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)                
      }                                               
    }