Last active
May 30, 2020 18:40
-
-
Save elliotchance/0e88ca11b5ed68c87056 to your computer and use it in GitHub Desktop.
A simple server in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} | |
}() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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