使用Golang将JSON发送到Unix套接字

问题描述:

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?

我正在尝试编写golang程序,以通过向以下命令发送命令来控制 mpv code> Unix套接字运行在 / tmp / mpvsocket code>。 p>

这是我到目前为止已经尝试过的操作: p>

  func main(){
c,err:= net.Dial(“ unix”,“ / tmp / mpvsocket”)
 if err!= nil {
 panic(err)
} 
延迟c.Close  ()
 
 _,err = c.Write([] byte(`{“ command”:[“ quit”]}`)))
 if err!= nil {
 log.Fatal(“写入错误 :“,err)
} 
} 
  code>  pre> 
 
 

这应该会导致mpv退出但什么也没发生。 p>

这 可以通过命令行发出命令以获得预期结果: p>

  echo'{“ command”:[“ quit”]}''|  socat-/ tmp / mpvsocket 
  code>  pre> 
 
 

它使用 socat code>将JSON发送到套接字。 如何使用Golang将其发送到套接字? p> div>

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

The fixed line:

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

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"]}` + "
"))
  if err != nil {                                 
    log.Fatal("write error:", err)                
  }                                               
}