REST API
Create a RESTful server in Go
Learn the theory behind REST as Mihalis Tsoukalos explains how to develop a concurrent RESTful server in Go.
Part One!
Don’t miss next issue, subscribe on page 26!
OUR EXPERT
Mihalis Tsoukalos is a systems engineer and technical writer. He’s the author of Go Systems Programming and Mastering Go. You can reach him at @mactsouk.
QUICK TIP
The official Go web sites are https://golang. org and https:// go.dev. You can also read The Go Programming Language by Alan Donovan and Brian Kernighan as well as Mastering Go by yours truly!
This month’s tutorial covers how to go about developing RESTful servers in Go. The second part will show how to develop command line clients to access this RESTful server. Remember that the single most important task of a RESTful server is the definition of the REST API. With that in mind, let’s begin learning about RESTful services.
REST, or REpresentational State Transfer, is an architecture for designing web services. REST isn’t tied to any OS or system architecture and isn’t a protocol; however, to implement a RESTful service, you need to use a protocol such as HTTP.
Additionally, REST can work with any data format. Usually REST means JSON over HTTP. There are also times where data is exchanged in plain text format, usually when the exchanged data is simple and there’s no need for using JSON records. Therefore, when developing RESTful servers in Go, you need to create the appropriate Go structures and perform the necessary marshalling and unmarshalling operations for the exchange of JSON data.
Go for develop
Go is ideal for developing both servers and clients for REST APIs for many reasons. Go works well with JSON data and supports concurrency by design, to name but two. As a result, all RESTful servers are concurrent without needing any extra code because the packages used for serving client requests operate concurrently. However, the principles of concurrent data sharing still apply and you shouldn’t share variables carelessly.
The first version of the server is going to use packages of the standard Go library. The second RESTful server is going to use an external Go package that’s much better than the default Go package. This first version, which is used of illustrating the ideas behind the development of RESTful services, is going to support the following endpoints:
>/time: this endpoint returns the current date and time to the client. It’s mainly used for testing that the server and the client can communicate without issues. /insert: this enables you to insert a new record to the server. As a result, it requires a JSON record as input.
>/list: this last endpoint sends the contents of a map with the data to the client.
>Finally, there’s a default handler for all endpoints that don’t match an existing one, which in the default Go router is associated with the / endpoint.