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

main.go
package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case "POST":
			r.ParseForm()
			fmt.Fprintf(w, "Hello %s!", r.FormValue("name"))
		default:
			fmt.Fprintf(w, "Hello World!")
		}
	})

	http.ListenAndServe(":8080", nil)
}
323 chars
21 lines

In this example, we create a simple HTTP server using the net/http package. When a request is made to the root of the server, we check the method of the request. If it's a POST request, we parse the form data with r.ParseForm() and read the value of the name field with r.FormValue("name"). We then respond with a message that includes the name provided. If it's not a POST request, we simply respond with "Hello World!"

To run this server, simply save the code above to a file (e.g. server.go) and run it with go run server.go. The server will then be accessible at http://localhost:8080.

gistlibby LogSnag