Created
August 28, 2015 21:19
-
-
Save johnandersen777/359c05559d29d65f96ce to your computer and use it in GitHub Desktop.
Redirect stdout to websocket in go, great for logging in gomobile
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 ( | |
"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