Member-only story
Go (Golang) is an excellent choice for building RESTful APIs due to its performance, concurrency support, and simplicity. In this guide, we’ll walk through creating a RESTful API from scratch using Go’s net/http
package and the Echo framework.
1. Setting Up the Go Project
Before we start, make sure you have Go installed. You can check by running:
go version
Initialize a Go Module
mkdir go-rest-api && cd go-rest-api
go mod init github.com/yourname/go-rest-api
2. Creating a Simple API with net/http
Go’s standard library provides the net/http
package, which is great for building lightweight APIs.
Basic API with net/http
package main
import (
"encoding/json"
"net/http"
}
type Message struct {
Message string `json:"message"`
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(Message{Message: "Hello, World!"})
}
func main() {
http.HandleFunc("/hello", helloHandler)
http.ListenAndServe(":8080", nil)
}
Run the API:
go run main.go
Visit http://localhost:8080/hello to see the JSON response.