From 7770d0dc422d6be5d5d6f4c156a1c89ded765cd6 Mon Sep 17 00:00:00 2001 From: "C. Torres" Date: Fri, 13 Dec 2024 20:45:36 -0300 Subject: [PATCH] Log when accepting a connection Add a log message with the remote address once a new websocket connection is established. Signed-off-by: C. Torres --- log.go | 19 ------------------- log/log.go | 20 ++++++++++++++++++++ main.go | 8 +++++--- 3 files changed, 25 insertions(+), 22 deletions(-) delete mode 100644 log.go create mode 100644 log/log.go diff --git a/log.go b/log.go deleted file mode 100644 index 41642b7..0000000 --- a/log.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "fmt" - "log" - "os" -) - -const ( - // sep holds white space used as log type separator. - sep = " " -) - -var ( - // logInfo is used to log stable runtime information. - logInfo = log.New(os.Stdout, fmt.Sprintf("%s%s", "info", sep), 0) - // logErr is used to log errors. - logErr = log.New(os.Stdout, fmt.Sprintf("%s%s", "error", sep), 0) -) diff --git a/log/log.go b/log/log.go new file mode 100644 index 0000000..8ffde89 --- /dev/null +++ b/log/log.go @@ -0,0 +1,20 @@ +// Package log instantiates global loggers for stable and error information. +package log + +import ( + "fmt" + "log" + "os" +) + +const ( + // sep holds white space used as log type separator. + sep = " " +) + +var ( + // Info is used to log stable runtime information. + Info = log.New(os.Stdout, fmt.Sprintf("%s%s", "info", sep), 0) + // Err is used to log errors. + Err = log.New(os.Stdout, fmt.Sprintf("%s%s", "error", sep), 0) +) diff --git a/main.go b/main.go index dfcddfb..306dfb6 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ import ( "fmt" "net" "net/http" + "wssrv/log" "wssrv/ws" "wssrv/wshttp" @@ -51,14 +52,14 @@ func acceptWsCon(tCon net.Conn) *websocket.Conn { for con == nil { if req, err = http.ReadRequest(r); err != nil { eMsg = fmt.Sprintf("unable to read request: %v", err) - logErr.Print(eMsg) + log.Err.Print(eMsg) http.Error(rw, fmt.Sprintf("error: %s", eMsg), http.StatusBadRequest) continue } if con, err = websocket.Upgrade(rw, req, nil, defBufSiz, defBufSiz); err != nil { eMsg = fmt.Sprintf("unable to create websocket connection: %v", err) - logErr.Print(eMsg) + log.Err.Print(eMsg) http.Error(rw, fmt.Sprintf("error: %s", eMsg), http.StatusBadRequest) } } @@ -75,11 +76,12 @@ func main() { listenAddr = fmt.Sprintf("%s:%d", defHost, port) ) - logInfo.Printf("listening on '%s'", listenAddr) + log.Info.Printf("listening on '%s'", listenAddr) if tCon, err = acceptTcpCon(listenAddr); err != nil { panic(err) } con = acceptWsCon(tCon) + log.Info.Printf("connected to '%s'", con.RemoteAddr()) defer con.Close() fmt.Println(ws.SendStdinLines(con))