2017-10-25 4 views
0

나는 yaml 설정 파일에 지정할 Go 파일을 실행하고 바이트 단위의 구조체를 보내고 싶다. 내가 어떻게 할 수 있니?Go Stdin Stdout communication

client.Subscribe(NewTopic(a), func(c *Client, msg Message) { 
      cmd := exec.Command(v.Action) 

      // I actually want to send [msg] to it so it can be used there 
      cmd.Stdin = bytes.NewReader(msg.Bytes()) 

      if err := cmd.Start(); err != nil { 
       c.Logger.Infof("Error while executing action: %v", err) 
      } else { 
       c.Logger.Info("Executed command") 
      } 

      // I want to handle responses from the called binary 
      var out bytes.Buffer 
      cmd.Stdout = &out 
      c.Logger.Infof("Response: %v", out) 
     }) 

I :이 내 코드입니다

subscribers: 
    temp: 
    topics: 
     - pi/+/temp 
    action: ./temp/tempBinary 

:

는 나는이

에 대한 표준 입력과 표준 출력을 사용할 수 그러나 YAML의 설정을 알아낼 수 없다는 생각 얼마나 정확하게 이것을 할 수 있는지 알 수 없습니다.

+0

그래서 Message.Bytes의 구현을 찾고 있습니까? 모든 메시지를 나타낼 수있는 인코딩이 가능합니다. [인코딩/* 패키지] (https://golang.org/pkg/encoding/#pkg-subdirectories)를 확인하십시오. 인기있는 선택은 encoding/json과 encoding/gob입니다. – Peter

+0

두 번째 생각에서 인코딩/gob은 모든 동작이 Go 프로그램 인 경우에만 유용합니다. – Peter

답변

0

이 당신이 뭔가 같은 것 https://golang.org/pkg/os/exec/#example_Cmd_StdinPip, https://golang.org/pkg/os/exec/#example_Cmd_StdoutPipehttps://golang.org/pkg/io/ioutil/#example_ReadAll

괜찮은 시작에 필요한의 좋은 예입니다

stdin, err := cmd.StdinPipe() 
if err != nil { 
    log.Fatal(err) 
} 
stdout, err := cmd.StdoutPipe() 
if err != nil { 
    log.Fatal(err) 
} 
defer stdin.Close() 
io.WriteString(stdin, msg.String()) 

b, err := ioutil.ReadAll(stdout) 
if err != nil { 
    log.Fatal(err) 
} 
c.Logger.Infof("Response %s", stdout) 

는 그러나이 솔루션은 심지어 가장자리 경우를 처리하기 시작하지 않습니다 파이프가 조기에 닫히는 등의 문제가 발생할 수 있습니다.

이 비디오는 다음과 같은 것들을 통해 좋은 대화를 나눌 수 있습니다 : https://www.youtube.com/watch?v=LHZ2CAZE6Gs&feature=youtu.be&list=PL6