Last active
June 12, 2025 20:21
-
-
Save blinkinglight/ed7bf4c9295a67ca0f5bf3221c9fcd58 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"io" | |
"os/exec" | |
"github.com/nats-io/nats.go" | |
) | |
type NWriter struct { | |
nc *nats.Conn | |
} | |
func (nw *NWriter) Write(p []byte) (n int, err error) { | |
err = nw.nc.Publish("updates", p) | |
if err != nil { | |
return 0, err | |
} | |
return len(p), nil | |
} | |
func main() { | |
nc, err := nats.Connect("nats://localhost:4222") | |
if err != nil { | |
panic(err) | |
} | |
defer nc.Close() | |
// echo | |
cmd := exec.Command("cat", "-") | |
in, _ := cmd.StdinPipe() | |
out, _ := cmd.StdoutPipe() | |
_, err = nc.Subscribe("in", func(m *nats.Msg) { | |
in.Write(m.Data) // Write the received message to the command's stdin | |
println("Received message:", string(m.Data)) | |
}) | |
if err != nil { | |
panic(err) | |
} | |
nw := &NWriter{nc: nc} | |
go func() { | |
_, err := io.Copy(nw, out) // Copy data from stdout to nats | |
if err != nil { | |
println("Error copying data:", err.Error()) | |
} | |
}() | |
cmd.Start() | |
if err := cmd.Wait(); err != nil { | |
println("Command finished with error:", err.Error()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment