Skip to content

Instantly share code, notes, and snippets.

@night-codes
Forked from miguelmota/server.go
Created October 11, 2021 09:37
Show Gist options
  • Save night-codes/683428f933e54ac0883ef37d26920a8f to your computer and use it in GitHub Desktop.
Save night-codes/683428f933e54ac0883ef37d26920a8f to your computer and use it in GitHub Desktop.
Golang TCP server example
package server
import (
"bufio"
"fmt"
"log"
"net"
)
// Server ...
type Server struct {
host string
port string
}
// Client ...
type Client struct {
conn net.Conn
}
// Config ...
type Config struct {
Host string
Port string
}
// New ...
func New(config *Config) *Server {
return &Server{
host: config.Host,
port: config.Port,
}
}
// Run ...
func (server *Server) Run() {
listener, err := net.Listen("tcp", fmt.Sprintf("%s:%s", server.host, server.port))
if err != nil {
log.Fatal(err)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
log.Fatal(err)
}
client := &Client{
conn: conn,
}
go client.handleRequest()
}
}
func (client *Client) handleRequest() {
reader := bufio.NewReader(client.conn)
for {
message, err := reader.ReadString('\n')
if err != nil {
client.conn.Close()
return
}
fmt.Printf("Message incoming: %s", string(message))
client.conn.Write([]byte("Message received.\n"))
}
}
package server
import (
"testing"
)
func TestServer(t *testing.T) {
server := New(&Config{
Host: "localhost",
Port: "3333",
})
server.Run()
}
// echo "hello world" | nc localhost 3333
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment