golang-exercises/query-cpu/cmd/server.go

51 lines
954 B
Go

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
}