In this post, we will look at a simple go program that makes a post request with no additional library.
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
)
func main() {
//Create a body using the json marshal.
requestBody, err := json.Marshal(map[string]string{
"title": "tettjam",
"userId": "15",
"body": "Hello from go prohem",
})
if err != nil {
log.Fatal(err)
}
// create a timeout
timeout := time.Duration(5 * time.Second)
// if you are making a request to an http url you would need to skip
// https check, below InsecureSkipvVerify:ture will do that. it is not a safe way to use in production.
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
//create a client
client := http.Client{Timeout: timeout, Transport: tr}
// prepare the request
req, err := http.NewRequest(
"POST",
"https://jsonplaceholder.typicode.com/posts",
bytes.NewBuffer(requestBody))
req.Header.Set("content-type", "application/json")
if err != nil {
log.Fatal(err)
}
//Send the HTTP Request returns a response(nill or body) or err
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
// close the respones body if the response has a body insted of nil.
defer resp.Body.Close()
// print the status code to check if the resource was created.
fmt.Println(resp.Status)
}