HTTP servers sample

This commit is contained in:
Eli Bendersky
2019-06-01 05:27:03 -07:00
committed by Mark McGranaghan
parent 552611bc1c
commit 973da6773f
7 changed files with 260 additions and 1 deletions

View File

@@ -0,0 +1,50 @@
// Writing a basic HTTP server is very easy using the
// `net/http` package.
package main
import (
"fmt"
"net/http"
)
// A fundamental concept in `net/http` servers is
// *handlers*. A handler is an object implementing the
// `http.Handler` interface. A very common way to write
// a handler is by using the `http.HandlerFunc` adapter
// on functions with the appropriate signature.
func hello(w http.ResponseWriter, req *http.Request) {
// Functions serving as handlers take a
// `http.ResponseWriter` and a `http.Request` as
// arguments. The response writer is used to fill in the
// HTTP response. Here out simple response is just
// "hello\n".
fmt.Fprintf(w, "hello\n")
}
func headers(w http.ResponseWriter, req *http.Request) {
// This handler does something a little more
// sophisticated by reading all the HTTP request
// headers and echoing them into the response body.
for name, headers := range req.Header {
for _, h := range headers {
fmt.Fprintf(w, "%v: %v\n", name, h)
}
}
}
func main() {
// We register our handlers on server routes using the
// `http.HandleFunc` convenience function. It sets up
// the *default router* in the `net/http` package and
// takes a function as an argument.
http.HandleFunc("/hello", hello)
http.HandleFunc("/headers", headers)
// Finally, we call the `ListenAndServe` with the port
// and a handler. `nil` tells it to use the default
// router we've just set up.
http.ListenAndServe(":8090", nil)
}

View File

@@ -0,0 +1,2 @@
1bffba1944537a9f9d7166a67d7a2b9f4ce2d70e
hg47WDVcY_W

View File

@@ -0,0 +1,6 @@
# Run the server in the background.
$ go run examples/http-servers/http-servers.go &
# Access the `/hello` route.
$ curl localhost:8090/hello
hello