make a http request with a custom body as html in go

Here's an example of making an HTTP request with a custom HTML body in Go:

main.go
package main

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

func main() {
    // Define the URL and payload
    url := "http://example.com"
    payload := []byte("<html><body><h1>Hello, World!</h1></body></html>")

    // Create the HTTP request with the custom HTML body
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
    if err != nil {
        fmt.Println("Error creating HTTP request:", err)
        return
    }

    // Set the Content-Type header to "text/html"
    req.Header.Set("Content-Type", "text/html")

    // Use the default HTTP client to send the request
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Error sending HTTP request:", err)
        return
    }

    // Print the HTTP response status code and body
    defer resp.Body.Close()
    fmt.Println("Status code:", resp.StatusCode)
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Error reading HTTP response body:", err)
        return
    }
    fmt.Println("Body:", string(body))
}
1074 chars
42 lines

In this example, we create an HTTP POST request to "http://example.com" with the HTML body "<html><body><h1>Hello, World!</h1></body></html>". We set the Content-Type header of the request to "text/html" so the server knows how to parse the request body. Finally, we use the default HTTP client to send the request and print the status code and response body.

related categories

gistlibby LogSnag