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

huangapple go评论66阅读模式
英文:

Send JSON to a unix socket with golang

问题

我正在尝试编写一个使用Golang控制mpv的程序,通过向运行在/tmp/mpvsocket的Unix套接字发送命令来实现。

这是我目前尝试的代码:

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

这应该会导致mpv退出,但是没有任何反应。

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

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

它使用socat将JSON发送到套接字。如何使用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?

答案1

得分: 1

感谢@AndySchweig在上面的评论中提供的帮助,我需要在我的JSON之后添加一个新行。

修正后的代码行:

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

修正后的完整代码块:

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

英文:

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

huangapple
  • 本文由 发表于 2017年1月22日 00:55:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/41782004.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定