create a http server and read the request body as form url encoded in go

Here's an example of how to create an HTTP server using the net/http package in Go and read the request body as form url-encoded:

main.go
package main

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

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // Read the form-encoded request body
        if err := r.ParseForm(); err != nil {
            http.Error(w, "Failed to parse form-encoded body", http.StatusBadRequest)
            return
        }

        // Read the form-encoded values
        values := r.PostForm

        // Log the form-encoded values
        fmt.Printf("Form values: %v\n", values)

        // Send a response
        fmt.Fprint(w, "Hello, World!")
    })

    // Start the server
    log.Fatal(http.ListenAndServe(":8080", nil))
}
662 chars
30 lines

In the http.HandleFunc callback function, we first parse the request body using r.ParseForm(). This populates the r.PostForm map with the form-encoded values. We then log these values and send a "Hello, World!" response. Finally, we start the server using http.ListenAndServe.

gistlibby LogSnag