Added logging capabilities to server
This commit is contained in:
parent
61bf3a0276
commit
89fce7631b
|
@ -6,10 +6,13 @@ package cmd
|
|||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"github.com/spf13/cobra"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// serverCmd represents the server command
|
||||
|
@ -42,7 +45,6 @@ func init() {
|
|||
}
|
||||
|
||||
func server() {
|
||||
fmt.Println()
|
||||
ln, err := net.Listen("tcp", ":8080")
|
||||
catchErr(err)
|
||||
fmt.Println("Listening on port 8080...")
|
||||
|
@ -56,9 +58,14 @@ func server() {
|
|||
func handleConn(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
message, err := bufio.NewReader(conn).ReadString('\n')
|
||||
message = strings.TrimRight(message, "\n")
|
||||
catchErr(err)
|
||||
conn_IP := getIP(conn)
|
||||
final_message := fmt.Sprintf("Received connection from %v with message: %v", conn_IP, message)
|
||||
t := time.Now()
|
||||
date := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
|
||||
|
||||
final_message := fmt.Sprintf("[%v] Received connection from %v with message: %v", date, conn_IP, message)
|
||||
writer(final_message)
|
||||
reply_message := fmt.Sprintf("Your message was sent successfully\n")
|
||||
conn.Write([]byte(reply_message))
|
||||
fmt.Println(final_message)
|
||||
|
@ -81,3 +88,12 @@ func catchErr(err error) (errHappened bool) {
|
|||
}
|
||||
return errHappened
|
||||
}
|
||||
|
||||
func writer(logstring string) {
|
||||
file, err := os.OpenFile("./connections.log", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0640)
|
||||
if err != nil {
|
||||
log.Fatalf("Error occurred: %v\n", err)
|
||||
}
|
||||
defer file.Close()
|
||||
file.WriteString(logstring)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue