Created
September 13, 2013 02:16
-
-
Save cespare/6546152 to your computer and use it in GitHub Desktop.
Example of how one might do websocket logging when using go-apachelog for http logging.
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" | |
| "log" | |
| "net/http" | |
| "os" | |
| "time" | |
| "code.google.com/p/go.net/websocket" | |
| apachelog "github.com/cespare/go-apachelog" | |
| ) | |
| const addr = "localhost:8888" | |
| // Where to write all the logs. | |
| var out = os.Stderr | |
| func init() { log.SetOutput(out) } | |
| type wsHandlerFunc func(io.Writer, []byte) error | |
| func EchoHandler(w io.Writer, msg []byte) error { | |
| _, err := w.Write(msg) | |
| return err | |
| } | |
| func wsLog(ws *websocket.Conn, format string, args ...interface{}) { | |
| args = append([]interface{}{ws.RemoteAddr()}, args...) | |
| log.Printf("[websocket] (%s) "+format, args...) | |
| } | |
| func MakeWSHandler(handleFunc wsHandlerFunc) websocket.Handler { | |
| return func(ws *websocket.Conn) { | |
| wsLog(ws, "connection opened") | |
| totalStart := time.Now() | |
| var totalBytes uint64 | |
| buf := make([]byte, 1024) | |
| for { | |
| // TODO: handle frames larger than buf as a single message and call to handleFunc | |
| n, err := ws.Read(buf) | |
| if err != nil { | |
| if err == io.EOF { | |
| break | |
| } else { | |
| wsLog(ws, "error: %s", err) | |
| return | |
| } | |
| } | |
| start := time.Now() | |
| if err := handleFunc(ws, buf); err != nil { | |
| wsLog(ws, "error: %s", err) | |
| return | |
| } | |
| elapsed := time.Since(start) | |
| wsLog(ws, "message %d %.4f", n, elapsed.Seconds()) | |
| totalBytes += uint64(n) | |
| } | |
| totalElapsed := time.Since(totalStart) | |
| wsLog(ws, "connection closed %d %.4f", totalBytes, totalElapsed.Seconds()) | |
| } | |
| } | |
| func Handle(w http.ResponseWriter, r *http.Request) { | |
| w.Write([]byte("hello")) | |
| } | |
| func main() { | |
| mux := http.NewServeMux() | |
| mux.Handle("/ws", MakeWSHandler(EchoHandler)) | |
| mux.HandleFunc("/a", Handle) | |
| logger := apachelog.NewHandler(mux, out) | |
| server := &http.Server{ | |
| Handler: logger, | |
| Addr: addr, | |
| } | |
| log.Fatal(server.ListenAndServe()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment