golang-exercises/chat-tests/cmd/serverFunc.go

69 lines
1.1 KiB
Go

package cmd
import (
"fmt"
"log"
"net"
"time"
)
var (
listenPort string = "1302"
)
type Creator interface {
CreateUser()
}
type User struct {
Username string
IP string
}
type Message struct {
Contents string
Date time.Time
}
func (u User) CreateUser(usr string, ip string) User {
u.Username = usr
u.IP = ip
return u
}
func Server() {
ln, err := net.Listen("tcp", ":"+listenPort)
if err != nil {
log.Fatalf("Error happened trying to listen on port: %v\n", err)
}
defer ln.Close()
fmt.Printf("Listening on port %v...\n", listenPort)
for {
conn, err := ln.Accept()
if err != nil {
log.Fatalf("Error happened trying to accept connection: %v\n", err)
}
go handleConn(conn)
}
}
func getUserInput() {
}
func handleConn(conn net.Conn) {
defer conn.Close()
newUserTemplate := new(User)
newUser := newUserTemplate.CreateUser("Tom", getIP(conn))
fmt.Printf("Received connection from %v at %v\n", newUser.Username, newUser.IP)
fmt.Fprintln(conn, "Hello buddy!")
}
func getIP(conn net.Conn) (IP string) {
if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
IP = fmt.Sprintf("%v", addr.IP)
}
return IP
}