Introduction ๐
In today's world, knowing how to write a server-side application is not enough. With the rise of containerization and the growing popularity of Docker, it's beneficial for developers to understand how to run their applications inside Docker containers. This tutorial will guide beginners through creating a RESTful API using Go (Golang) and then dockerizing it.
Prerequisites
Before we start, make sure you have Go and Docker installed on your machine. If you haven't, you can download Go from the official Go website and Docker from Docker's official website.
Video about this topic ๐
Step 1: Writing Our Go RESTful API ๐ฅ
To begin, we will develop a simple RESTful API to manage "tasks". Each task will have three attributes: ID, Title, and Status.
Setting Up Our Project
Create a new directory for our project and navigate into it:
mkdir go-rest-api && cd go-rest-api
Creating the Go Application
Create a new file named main.go
. This file will hold our server code:
package main
import (
"fmt"
"encoding/json"
"net/http"
"io/ioutil"
"strings"
)
type Task struct {
ID string `json:"id"`
Title string `json:"title"`
Status string `json:"status"`
}
var tasks []Task
func tasksHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
json.NewEncoder(w).Encode(tasks)
case "POST":
body, _ := ioutil.ReadAll(r.Body)
var task Task
json.Unmarshal(body, &task)
tasks = append(tasks, task)
json.NewEncoder(w).Encode(tasks)
}
}
func taskHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
id := strings.TrimPrefix(r.URL.Path, "/tasks/")
for _, item := range tasks {
if item.ID == id {
json.NewEncoder(w).Encode(item)
return
}
}
http.Error(w, "Task not found.", http.StatusNotFound)
default:
http.Error(w, "Invalid request method.", http.StatusMethodNotAllowed)
}
}
func main() {
tasks = append(tasks, Task{ID: "1", Title: "Task one", Status: "Pending"})
http.HandleFunc("/tasks/", taskHandler)
http.HandleFunc("/tasks", tasksHandler)
fmt.Println("Server listening on port 8000")
http.ListenAndServe(":8000", nil)
}
In this code, we've defined two HTTP endpoints:
/tasks
: This endpoint acceptsGET
andPOST
requests.GET
requests return all tasks, whilePOST
requests add a new task to the list./tasks/{id}
: This endpoint acceptsGET
requests and returns the task with the matching ID.
To test the server, run go run main.go
in your terminal. The server will start listening on http://localhost:8000
.
Step 2: Dockerizing the Go Application โ๏ธ
Now, let's dockerize our application. This involves creating a Dockerfile, building an image from that Dockerfile, and running a Docker container from the image.
Writing the Dockerfile
Create a new file in the project directory named Dockerfile
. This file will define how Docker should build our image:
FROM golang:latest
RUN mkdir /app
ADD . /app
WORKDIR /app
RUN go build -o main .
CMD ["/app/main"]
In this Dockerfile:
We startfrom the
golang:latest
base image, which includes Go latest version.We create a new directory
/app
inside the Docker image to hold our application code.We copy our local project files into the
/app
directory in the image.We set the working directory inside the image to
/app
.We use the
go build -o main .
command to compile our Go code into a binary namedmain
.Finally, we tell Docker to execute the
main
binary when the Docker container is started.
Building the Docker Image
Next, build the Docker image using the Dockerfile:
docker build -t go-rest-api .
Here, -t go-rest-api
names the image "go-rest-api", and .
tells Docker to look for the Dockerfile in the current directory.
Running the Docker Container
Finally, we can run our application inside a Docker container using the image we just built:
docker run -p 8000:8000 go-rest-api
This command tells Docker to run a new container from the go-rest-api
image and map port 8000 inside the Docker container to port 8000 on our machine.
Visit http://localhost:8000/tasks
in your web browser or use a tool like curl or Postman to confirm that the server is working as expected.
Conclusion โณ
And that's it! You have now created a simple RESTful API using Go and dockerized it. This tutorial introduced you to the basics of Go programming and Docker containerization. With this knowledge, you can now create more complex applications and run them in Docker containers, harnessing the power of containerization for development, testing, and deployment.
That's it for now.
You can Buy Me a Coffee if you want to and please don't forget to follow me on YouTube, Twitter, and LinkedIn also.
If you have any questions or would like to share your own experiences, feel free to leave a comment below. I'm here to support and engage with you.
Happy Dockerizing!