make a http request with a custom body as json and return a json response in go

main.go
import (
	"bytes"
	"encoding/json"
	"net/http"
)

type MyRequest struct {
	Field1 string `json:"field1"`
	Field2 int    `json:"field2"`
}

type MyResponse struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

func makeHTTPRequest() (*MyResponse, error) {

	// Define the request body
	requestBody := &MyRequest{Field1: "value1", Field2: 123}

	// Marshal the request body into a JSON string
	jsonBody, err := json.Marshal(requestBody)
	if err != nil {
		return nil, err
	}

	// Create the request object
	req, err := http.NewRequest("POST", "https://example.com/api", bytes.NewBuffer(jsonBody))
	if err != nil {
		return nil, err
	}

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

	// Execute the request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	// Decode the response body into a MyResponse object
	var responseBody MyResponse
	err = json.NewDecoder(resp.Body).Decode(&responseBody)
	if err != nil {
		return nil, err
	}

	return &responseBody, nil
}
1110 chars
54 lines

This code creates an HTTP request with a custom JSON body and returns a JSON response. It defines a MyRequest struct which is marshaled into a JSON string and included as the request body. The Content-Type request header is set to application/json to indicate to the server that we're sending JSON data. After executing the request, the response body is decoded into a MyResponse struct.

gistlibby LogSnag