Skip to content
Thomas Cherryhomes edited this page Feb 13, 2021 · 1 revision

The following Go program can be used as a test harness for GET and POST requests.

For GET requests, each query parameter is printed to stdout. The string "This is the GET body." is returned as the body of the GET request.

For POST requests, the body of the POST request is printed to stdout. The string "This is the POST body." is returned as the body of the POST request.

package main

import (
        "fmt"
        "io/ioutil"
        "log"
        "net/http"
)

func helloWorld(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path != "/" {
                http.NotFound(w, r)
                return
        }
        switch r.Method {
        case "GET":
                for k, v := range r.URL.Query() {
                        fmt.Printf("%s: %s\n",k, v)
                }
                w.Write([]byte("This is the GET body.\r\n"))
        case "POST":
                reqBody, err := ioutil.ReadAll(r.Body)
                if err != nil {
                        log.Fatal(err)
                }

                fmt.Printf("%s\n", reqBody)
                w.Write([]byte("This is the POST body.\r\n"))
        default:
                w.WriteHeader(http.StatusNotImplemented)
                w.Write([]byte(http.StatusText(http.StatusNotImplemented)))
        }
}

func main() {
        http.HandleFunc("/", helloWorld)
        http.ListenAndServe(":8000", nil)
}
Clone this wiki locally