From 15ea54b5ae5ef519d87110e92a601d111790177f Mon Sep 17 00:00:00 2001 From: raul Date: Tue, 23 Apr 2024 08:30:36 +0200 Subject: [PATCH] Add ability to receive username --- chat-tests/cmd/serverFunc.go | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/chat-tests/cmd/serverFunc.go b/chat-tests/cmd/serverFunc.go index b6707fa..7d3abe8 100644 --- a/chat-tests/cmd/serverFunc.go +++ b/chat-tests/cmd/serverFunc.go @@ -1,9 +1,11 @@ package cmd import ( + "bufio" "fmt" "log" "net" + "strings" "time" ) @@ -47,6 +49,17 @@ func Server() { } } +func getUsername(conn net.Conn) string { + conn.Write([]byte("What's your name?\n\r")) + conn.Write([]byte("Choice: ")) + name, err := bufio.NewReader(conn).ReadString('\n') + if err != nil { + log.Fatalf("Error occurred getting username: %v\n", err) + } + trimmedName := strings.TrimRight(name, "\n") + return trimmedName +} + func getUserInput() { } @@ -54,7 +67,7 @@ func getUserInput() { func handleConn(conn net.Conn) { defer conn.Close() newUserTemplate := new(User) - newUser := newUserTemplate.CreateUser("Tom", getIP(conn)) + newUser := newUserTemplate.CreateUser(getUsername(conn), getIP(conn)) fmt.Printf("Received connection from %v at %v\n", newUser.Username, newUser.IP) fmt.Fprintln(conn, "Hello buddy!") } @@ -63,6 +76,5 @@ func getIP(conn net.Conn) (IP string) { if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok { IP = fmt.Sprintf("%v", addr.IP) } - return IP }