examples: add an HTTP server example
Show off the localhost TCP network support!
Change-Id: I2d98a735a2d3d0277680ee0c334da7cc39fe88e4
Reviewed-on: https://go-review.googlesource.com/c/playground/+/328950
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Alexander Rakoczy <alex@golang.org>
Trust: Dmitri Shuralyov <dmitshur@golang.org>
Trust: Filippo Valsorda <filippo@golang.org>
Run-TryBot: Dmitri Shuralyov <dmitshur@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
diff --git a/edit.html b/edit.html
index 677c2f4..14b5e4b 100644
--- a/edit.html
+++ b/edit.html
@@ -124,6 +124,7 @@
<option value="hello.txt">Hello, playground</option>
<option value="test.txt">Tests</option>
<option value="multi.txt">Multiple files</option>
+ <option value="http.txt">HTTP server</option>
<option value="image.txt">Display image</option>
<option value="sleep.txt">Sleep</option>
<option value="clear.txt">Clear</option>
diff --git a/examples/http.txt b/examples/http.txt
new file mode 100644
index 0000000..7c8f651
--- /dev/null
+++ b/examples/http.txt
@@ -0,0 +1,36 @@
+package main
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "os"
+)
+
+func main() {
+ http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, "Hello, playground")
+ })
+
+ log.Println("Starting server...")
+ l, err := net.Listen("tcp", "localhost:8080")
+ if err != nil {
+ log.Fatal(err)
+ }
+ go func() {
+ log.Fatal(http.Serve(l, nil))
+ }()
+
+ log.Println("Sending request...")
+ res, err := http.Get("http://localhost:8080/hello")
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ log.Println("Reading response...")
+ if _, err := io.Copy(os.Stdout, res.Body); err != nil {
+ log.Fatal(err)
+ }
+}