Programming

Small Go Script To Send Some JSON To An Endpoint

The following was written to act as a Google Cloud Function or Lambda, and sends a simple POST to a standard rest endpoint at https://krypted.com/api/v1/sites with the json defined in jsonObject. The endpoint can easily be changed in http.NewRequest or converted to a variable. The response to the POST is then returned as stdout.

package main

import (
"fmt"
"net/http"
"encoding/json"
)

func main() {
// Create a new HTTP client.
client := &http.Client{}

// Create a new JSON object.
jsonObject := map[string]string{
"name": "Krypted",
"site": "www.krypted.com",
}

// Marshal the JSON object to a string.
jsonString, err := json.Marshal(jsonObject)
if err != nil {
fmt.Println(err)
return
}

// Create a new POST request.
request, err := http.NewRequest("POST", "https://krypted.com/api/v1/sites", bytes.NewBuffer(jsonString))
if err != nil {
fmt.Println(err)
return
}

// Set the Content-Type header to application/json.
request.Header.Set("Content-Type", "application/json")

// Send the request.
response, err := client.Do(request)
if err != nil {
fmt.Println(err)
return
}

// Check the response status code.
if response.StatusCode != http.StatusOK {
fmt.Println("Error:", response.Status)
return
}

// Decode the response body into a JSON object.
var responseBody map[string]interface{}
err = json.NewDecoder(response.Body).Decode(&responseBody)
if err != nil {
fmt.Println(err)
return
}

// Print the response body.
fmt.Println("Response body:", responseBody)
}