Go has a built-in HTTP server in net/http
.
Here’s me playing around using it:
package main
import (
"fmt"
"net/http"
"strings"
)
func hello(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "hello\n")
}
func details(w http.ResponseWriter, req *http.Request) {
resp := []string{}
resp = append(resp, "Request Details:")
resp = append(resp, fmt.Sprintf("- Request proto: %s", req.Proto))
resp = append(resp, fmt.Sprintf("- Headers:"))
for name, val := range req.Header {
resp = append(resp, fmt.Sprintf("\t- %s: %s", name, val))
}
resp = append(resp, "\n")
fmt.Fprintf(w, strings.Join(resp, "\n"))
}
func main() {
http.HandleFunc("/hello", hello)
http.HandleFunc("/details", details)
fmt.Println("Started.")
http.ListenAndServe("127.0.0.1:9999", nil)
fmt.Println("Exiting.")
}
The /details
endpoint returns interesting stuff about the HTTP request, like its protocol and headers:
$ curl -s -H "X-Simas-Token: hunter2" localhost:9999/details
Request Details:
- Request proto: HTTP/1.1
- Headers:
- User-Agent: [curl/7.79.1]
- Accept: [*/*]
- X-Simas-Token: [hunter2]
There’s some fantastic examples of what this is capable of in Eli Bendersky’s post Serving static files and web apps in Go.