Skip to content

Instantly share code, notes, and snippets.

@elliotchance
Last active May 30, 2020 18:40
Show Gist options
  • Save elliotchance/0e88ca11b5ed68c87056 to your computer and use it in GitHub Desktop.
Save elliotchance/0e88ca11b5ed68c87056 to your computer and use it in GitHub Desktop.
A simple server in Go
package main
import (
"bufio"
"fmt"
"net"
)
func check(err error, message string) {
if err != nil {
panic(err)
}
fmt.Printf("%s\n", message)
}
func main() {
ln, err := net.Listen("tcp", ":8080")
check(err, "Server is ready.")
for {
conn, err := ln.Accept()
check(err, "Accepted connection.")
go func() {
buf := bufio.NewReader(conn)
for {
name, err := buf.ReadString('\n')
if err != nil {
fmt.Printf("Client disconnected.\n")
break
}
conn.Write([]byte("Hello, " + name))
}
}()
}
}
package main
import (
"bufio"
"fmt"
"net"
"time"
)
func check(err error, message string) {
if err != nil {
panic(err)
}
fmt.Printf("%s\n", message)
}
type ClientJob struct {
name string
conn net.Conn
}
func generateResponses(clientJobs chan ClientJob) {
for {
// Wait for the next job to come off the queue.
clientJob := <-clientJobs
// Do something thats keeps the CPU buys for a whole second.
for start := time.Now(); time.Now().Sub(start) < time.Second; {
}
// Send back the response.
clientJob.conn.Write([]byte("Hello, " + clientJob.name))
}
}
func main() {
clientJobs := make(chan ClientJob)
go generateResponses(clientJobs)
ln, err := net.Listen("tcp", ":8080")
check(err, "Server is ready.")
for {
conn, err := ln.Accept()
check(err, "Accepted connection.")
go func() {
buf := bufio.NewReader(conn)
for {
name, err := buf.ReadString('\n')
if err != nil {
fmt.Printf("Client disconnected.\n")
break
}
clientJobs <- ClientJob{name, conn}
}
}()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment