Sling Academy
Home/Golang/How to Build and Deploy a REST API in Go

How to Build and Deploy a REST API in Go

Last updated: November 27, 2024

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.

Next Article: Creating CI/CD Pipelines for Go Projects

Previous Article: Using Kubernetes for Go App Deployment

Series: Development and Debugging in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant