Added logging capabilities to server

This commit is contained in:
raul 2024-03-24 10:56:34 +01:00
parent 61bf3a0276
commit 89fce7631b
1 changed files with 19 additions and 3 deletions

View File

@ -6,10 +6,13 @@ package cmd
import ( import (
"bufio" "bufio"
"fmt" "fmt"
"github.com/spf13/cobra"
"log" "log"
"net" "net"
"os" "os"
"strings"
"time"
"github.com/spf13/cobra"
) )
// serverCmd represents the server command // serverCmd represents the server command
@ -42,7 +45,6 @@ func init() {
} }
func server() { func server() {
fmt.Println()
ln, err := net.Listen("tcp", ":8080") ln, err := net.Listen("tcp", ":8080")
catchErr(err) catchErr(err)
fmt.Println("Listening on port 8080...") fmt.Println("Listening on port 8080...")
@ -56,9 +58,14 @@ func server() {
func handleConn(conn net.Conn) { func handleConn(conn net.Conn) {
defer conn.Close() defer conn.Close()
message, err := bufio.NewReader(conn).ReadString('\n') message, err := bufio.NewReader(conn).ReadString('\n')
message = strings.TrimRight(message, "\n")
catchErr(err) catchErr(err)
conn_IP := getIP(conn) 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") reply_message := fmt.Sprintf("Your message was sent successfully\n")
conn.Write([]byte(reply_message)) conn.Write([]byte(reply_message))
fmt.Println(final_message) fmt.Println(final_message)
@ -81,3 +88,12 @@ func catchErr(err error) (errHappened bool) {
} }
return errHappened 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)
}