From 4ba20dfc76e80a50ccef45b53b8b3dcccb943a30 Mon Sep 17 00:00:00 2001 From: raul Date: Fri, 22 Mar 2024 15:38:28 +0100 Subject: [PATCH] Add tiny server to query-cpu exercise --- query-cpu/main.go | 1 + query-cpu/server.go | 50 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 query-cpu/server.go diff --git a/query-cpu/main.go b/query-cpu/main.go index 614a2a5..03a5cc8 100644 --- a/query-cpu/main.go +++ b/query-cpu/main.go @@ -14,4 +14,5 @@ func main() { } fmt.Println(cpuCores) + server() } diff --git a/query-cpu/server.go b/query-cpu/server.go new file mode 100644 index 0000000..b37252f --- /dev/null +++ b/query-cpu/server.go @@ -0,0 +1,50 @@ +package main + +import ( + "bufio" + "fmt" + "log" + "net" + "os" +) + +func server() { + fmt.Println() + ln, err := net.Listen("tcp", ":8080") + catchErr(err) + fmt.Println("Listening...") + for { + conn, err := ln.Accept() + catchErr(err) + go handleConn(conn) + } +} + +func handleConn(conn net.Conn) { + defer conn.Close() + message, err := bufio.NewReader(conn).ReadString('\n') + catchErr(err) + conn_IP := getIP(conn) + final_message := fmt.Sprintf("Received connection from %v with message: %v", conn_IP, message) + reply_message := fmt.Sprintf("Your message was sent successfully\n") + conn.Write([]byte(reply_message)) + fmt.Println(final_message) + +} + +func getIP(conn net.Conn) (IP string) { + if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok { + IP = fmt.Sprintf("%v", addr) + } + return IP +} + +func catchErr(err error) (errHappened bool) { + errHappened = false + if err != nil { + errHappened = true + log.Fatalf("Error: %v\n", err) + os.Exit(2) + } + return errHappened +}