Skip to content

Instantly share code, notes, and snippets.

@pdxjohnny
Created August 28, 2015 21:19
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pdxjohnny/359c05559d29d65f96ce to your computer and use it in GitHub Desktop.
Save pdxjohnny/359c05559d29d65f96ce to your computer and use it in GitHub Desktop.
Redirect stdout to websocket in go, great for logging in gomobile
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"time"
"github.com/pdxjohnny/microsocket/client"
)
func NewClient() *client.Conn {
ws := client.NewClient()
ws.Recv = func (m []byte) {}
ws.ClientId, _ = os.Hostname()
wsUrl := fmt.Sprintf("http://%s:%d/ws", "localhost", 8081)
err := ws.Connect(wsUrl)
if err != nil {
log.Println(err)
}
go ws.Read()
startMessage := fmt.Sprintf("Started %s", ws.ClientId)
ws.Write([]byte(startMessage))
return ws
}
func main() {
r, w, _ := os.Pipe()
os.Stdout = w
go func(reader io.Reader) {
logger := NewClient()
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
logger.Write([]byte(scanner.Text()))
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "There was an error with the scanner", err)
}
}(r)
fmt.Println("test")
time.Sleep(2 * time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment