Building and deploying a REST API using Go is a powerful way to create web services. Go, known for its simplicity and performance, provides a great ecosystem for developing scalable applications.

Install Go

Before starting, ensure you have Go installed on your system. You can download it from the official Go website.

Initialize Your Go Project

Start by creating a directory for your project and initializing a new Go module.

mkdir my-rest-api
cd my-rest-api
go mod init github.com/yourusername/my-rest-api

Create a Simple REST API

Let's build a simple REST API with a single endpoint that returns a list of users. Create a file named main.go and add the following code:

package main

import (
    "encoding/json"
    "net/http"
    "github.com/gorilla/mux"
    "log"
)

type User struct {
    ID   string `json:"id"`
    Name string `json:"name"`
}

var users = []User{
    {ID: "1", Name: "Alice"},
    {ID: "2", Name: "Bob"},
}

func getUsers(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(users)
}

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/users", getUsers).Methods("GET")
    log.Println("Server is starting...")
    log.Fatal(http.ListenAndServe(":8000", router))
}

Install the Gorilla Mux Package

Gorilla Mux is a powerful URL router and dispatcher. To use Gorilla Mux, you need to install it:

go get -u github.com/gorilla/mux

Run Your API Locally

You can now run your API using the Go run command:

go run main.go

The server will start on port 8000. You can access the endpoint by visiting http://localhost:8000/users in your browser or using a tool like Postman.

Deploy Your API

To deploy your API, you can use a cloud provider like AWS, Google Cloud, or Heroku. Creating a Docker container is a practical approach. First, create a Dockerfile:

FROM golang:1.19-alpine

WORKDIR /app

COPY go.mod .
COPY go.sum .
RUN go mod download

COPY . .

RUN go build -o /my-rest-api

EXPOSE 8000

CMD ["/my-rest-api"]

Build and Run the Docker Image

Build and run your Docker container with:

docker build -t my-rest-api .
docker run -p 8000:8000 my-rest-api

With Docker, you can easily deploy this container to any environment that supports containers, ensuring your Go REST API runs seamlessly across various platforms.

In conclusion, building a REST API in Go offers strong performance and speed. With the right tools and a little setup, you can quickly create and deploy an efficient web service.