Add tiny server to query-cpu exercise

This commit is contained in:
raul 2024-03-22 15:38:28 +01:00
parent 18bd5f98a3
commit 4ba20dfc76
2 changed files with 51 additions and 0 deletions

View File

@ -14,4 +14,5 @@ func main() {
}
fmt.Println(cpuCores)
server()
}

50
query-cpu/server.go Normal file
View File

@ -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
}