mchess-server/server/server.go

91 lines
1.5 KiB
Go
Raw Normal View History

2022-10-22 18:01:55 +00:00
package server
import (
"bufio"
"crypto/tls"
"fmt"
"io"
"log"
"net"
"os"
"strconv"
)
const (
port uint = 8080
certFile = "/home/m/.local_ca/localhost.crt"
keyFile = "/home/m/.local_ca/localhost.key"
)
func RunServer() error {
tls_cfg, err := configTls()
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
listener, err := listen(tls_cfg)
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
for {
connection, err := listener.Accept()
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
go handleConnection(connection)
}
}
func configTls() (*tls.Config, error) {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
log.Println("Error while loading x509 key pair")
log.Println(err)
return nil, err
}
return &tls.Config{Certificates: []tls.Certificate{cert}}, nil
}
func listen(tls_config *tls.Config) (net.Listener, error) {
listeningOnAddr := "localhost:" + strconv.FormatUint(uint64(port), 10)
listener, err := tls.Listen("tcp", listeningOnAddr, tls_config)
if err != nil {
return nil, err
}
fmt.Println("We started to listen on port", port)
return listener, nil
}
func handleConnection(connection net.Conn) {
testReader := *bufio.NewReader(connection)
for {
readBuf := make([]byte, 10)
if n, err := testReader.Read(readBuf); n > 0 {
fmt.Printf("Type of connection: %T\n", connection)
fmt.Println(n, " bytes read: ", readBuf)
if n > 0 {
switch err {
case nil:
case io.EOF:
fmt.Println(err)
default:
fmt.Println(err)
}
}
}
}
}