Connect Go Applications to Web APIs Using net/http and CData API Server



Go (often called Golang) is a modern, open-source programming language developed at Google that emphasizes simplicity, speed, and scalability. Its lightweight concurrency model and efficient memory management make it a popular choice across the industry for building cloud-native applications, high-performance APIs, and data-driven microservices.

By combining Go’s simplicity and efficiency with the flexibility of CData API Server, developers can bridge the gap between applications and data sources with minimal effort.

In this article, we explore how to use Go’s net/http and encoding/json packages to connect a Go application to a MySQL table exposed by CData API Server, retrieve the data as JSON, and parse it into Go structs for clean consumption. Please note that the same principles used here apply to any other source driver supported by the CData API Server.

Target API specifications

First, add a MySQL database as a connection in the CData API Server. From there, expose the Accounts table as a REST API endpoint. Once the table is published, you can consume it just like any other web API using Go.

You can get a list of accounts by sending a GET request to:

http://localhost:8080/api.rsc/new_schema_accounts

Authentication uses the custom header x-cdata-authtoken.

GET /api.rsc/new_schema_accounts?$top=2 HTTP/1.1
Host: localhost:8080
x-cdata-authtoken: "YOUR_TOKEN_HERE"
Accept: application/json

The root object has a property called value that contains an array of records. This data is directly sourced from the MySQL Accounts table, which is exposed as a REST (OData) endpoint. A sample response looks like this:

{
  "@odata.context": "http://localhost:8080/api.rsc/$metadata#new_schema_accounts",
  "value": [
    {
      "AccountID": 1,
      "AccountName": "Alice John",
      "Email": "[email protected]",
      "Balance": 2500.75,
      "CreatedAt": "2025-09-26T20:48:32.000+05:30"
    },
    {
      "AccountID": 2,
      "AccountName": "Bob Smith",
      "Email": "[email protected]",
      "Balance": 150,
      "CreatedAt": "2025-09-26T20:48:32.000+05:30"
    }
  ]
}

Packages used in API requests

Use Go’s built-in net/http package to send HTTP requests and encoding/json to parse the JSON responses. Both are part of the standard library, so no additional dependencies are required.

Project preparation

Set up a new Go project with the given commands:

mkdir AccountsAPIRequestSample
cd AccountsAPIRequestSample
go mod init AccountsAPIRequestSample
New-Item -ItemType File main.go

Prepare a structure to store the response

Define two structs:

  • AccountsRoot for the top-level JSON object.
  • Account for each record in the MySQL Accounts table.
type AccountsRoot struct {
    ODataContext string    `json:"@odata.context"`
    Value        []Account `json:"value"`
}

type Account struct {
    AccountID   int     `json:"AccountID"`
    AccountName string  `json:"AccountName"`
    Email       string  `json:"Email"`
    Balance     float64 `json:"Balance"`
    CreatedAt   string  `json:"CreatedAt"`
}

Why use JSON tags?

Go handles struct field names by exporting any field or function that starts with a capital letter, while treating lowercase fields as private.

When json.Unmarshal is called, it maps JSON keys only into exported fields. For example, if you define the field as value []Account (with lowercase v), the JSON parser does not populate it.

To ensure the JSON keys match properly, follow the given steps:

  • Capitalize the struct fields (Value, AccountID, AccountName, etc.).
  • Use struct tags like `json:"value"` or `json:"AccountID"` to explicitly map the JSON property names to the Go fields.

With these steps, the JSON response from the CData API Server (coming from the source table) correctly populates the Go structs.

Make an API request

While making an API request, include the authentication header (x-cdata-authtoken) by using http.NewRequest instead of http.Get.

url := "http://localhost:8080/api.rsc/new_schema_accounts?$top=2"
authHeaderName := "x-cdata-authtoken"
authHeaderValue := "YOUR_AUTHTOKEN" 

req, _ := http.NewRequest(http.MethodGet, url, nil)
req.Header.Set(authHeaderName, authHeaderValue)
req.Header.Set("Accept", "application/json")

client := new(http.Client)
resp, err := client.Do(req)

Check the status code to handle errors (e.g., unauthorized access if the token is incorrect) and always close the response body to prevent leaks.

Now, read the body and unmarshal the JSON into the Go structs.

Full source code

package main

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

func main() {
	fmt.Println("Start!")

	// MySQL Accounts table exposed via CData API Server
	url := "http://localhost:8080/api.rsc/new_schema_accounts?$top=2"
	authHeaderName := "x-cdata-authtoken"
	authHeaderValue := "YOUR_AUTHTOKEN"

	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		os.Exit(1)
	}
	req.Header.Set(authHeaderName, authHeaderValue)
	req.Header.Set("Accept", "application/json")

	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error making request:", err)
		os.Exit(1)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		fmt.Println("Error Response:", resp.Status)
		os.Exit(1)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading body:", err)
		os.Exit(1)
	}

	var out AccountsRoot
	if err := json.Unmarshal(body, &out); err != nil {
		fmt.Println("Error parsing JSON:", err)
		fmt.Println("Raw:", string(body))
		os.Exit(1)
	}

	pretty, _ := json.MarshalIndent(out, "", "  ")
	fmt.Println(string(pretty))
}

type AccountsRoot struct {
	ODataContext string    `json:"@odata.context"`
	Value        []Account `json:"value"`
}

type Account struct {
	AccountID   int     `json:"AccountID"`
	AccountName string  `json:"AccountName"`
	Email       string  `json:"Email"`
	Balance     float64 `json:"Balance"`
	CreatedAt   string  `json:"CreatedAt"`
}

Simplifying Data Access with Go and CData API Server

With CData API Server, you can expose data from 300+ databases, web applications, and SaaS platforms as a secure, standards-based API. For Go developers, this means you can integrate real-time data into your applications without building custom drivers or complex connectors.

Get started with a free 30-day trial of CData API Server to expose any source data as RESTful APIs and connect them to Go applications with ease. For assistance, our world-class CData Support Team is always available to help!