All You Need to Build a Simple REST API With Golang — Part I

$go mod init
go: creating new go.mod: module github.com/marcosap/go-rest
$ go run cmd/go-rest/main.go
2021/03/30 21:27:46 I'm go-rest, nice to meet you!
$ go get github.com/gorilla/mux
$ go run cmd/go-rest/main.go
2021/04/07 18:13:13 I'm go-rest, nice to meet you!
2021/04/07 18:13:13 Starting the API
  • An ApiRoute struct containing the url of the resource, and a handler function that will be used to set the routes that will be served by theAPI.
  • An interface called ApiResource that defines what any struct needs to provide in order to be used as a resource of the API. In this case a method that returns a array of ApiRoute’s.
$go run cmd/go-rest/main.go
2021/04/09 18:43:41 I'm go-rest, nice to meet you!
2021/04/09 18:43:41 Starting the API
$ curl http://localhost:9000/api/animals --silent | jq
[
{
"type": "dog",
"name": "Bob"
},
{
"type": "cat",
"name": "Felix"
}
]
$ go run cmd/go-rest/main.go 
2021/04/19 17:59:29 I'm go-rest, nice to meet you!
2021/04/19 17:59:29 Starting the API
$ curl http://localhost:9000/api/cars --silent | jq
[
{
"model": "Tucker Torpedo",
"year": "1948"
},
{
"model": "Ford GT40",
"year": "1966"
}
]
$ curl http://localhost:9000/api/animals/Bob --silent | jq
{
"type": "dog",
"name": "Bob"
}
$ curl http://localhost:9000/api/animals/Felix --silent | jq
{
"type": "cat",
"name": "Felix"
}

--

--

Software developer in constant evolution. Professional father. Mediocre musician =p

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Marcos Pereira

Marcos Pereira

Software developer in constant evolution. Professional father. Mediocre musician =p