How to create a generic JSON request function, over HTTP, in Go?
cristiancurteanu.com·7h·
Discuss: r/golang
Flag this post

Introduction

If you’ve been writing Go HTTP clients for a while, you’ve probably noticed a pattern: you’re constantly writing the same boilerplate code to marshal requests, handle responses, and unmarshal JSON. Each API integration becomes a repetitive dance of error handling and type assertions.

Since Go 1.18 introduced generics, we finally have the tools to eliminate this repetition while maintaining type safety. Let me show you how.

The Traditional Approach (And Why It’s Painful)

Let’s start with a typical HTTP client implementation you’ve probably written dozens of times:

type Header struct {
Key   string
Value string
}

func doJSONRequest(method string, url string, requestData interface{}, headers ...Header) (*http.Response, error) {
// Marshal request body
json...

Similar Posts

Loading similar posts...