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

main.go
package main

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

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

		// Check if request method is POST
		if r.Method == "POST" {

			// Read request body
			body, err := ioutil.ReadAll(r.Body)
			if err != nil {
				http.Error(w, "Failed to read request body", http.StatusBadRequest)
				return
			}

			// Convert request body to string containing HTML
			htmlString := string(body)

			// Print HTML string
			fmt.Println(htmlString)

			// Write response
			w.Write([]byte("Request body received as HTML"))
			return
		}

		// Write response for non-POST requests
		w.Write([]byte("Send a POST request with HTML body to this server"))

	})

	fmt.Println("Server started on port 8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}
819 chars
42 lines

In this code, a http.HandleFunc is used to handle incoming requests on the root path (/). The function first checks if the request method is POST. If it is, the request body is read using the ioutil.ReadAll method, and the resulting byte slice is converted to a string. This string then contains the HTML sent in the request body, which can be printed or further processed as necessary.

If the request method is not POST, the function simply writes a response indicating that a POST request with an HTML body is expected.

Finally, the server is started using http.ListenAndServe on port 8080.

related categories

gistlibby LogSnag