# Build Golang API using Gin and Docker
### Build Golang API
Gin is a popular golang framewrok (https://github.com/gin-gonic/gin).
This code (main.go) is to build a basic GET verb API to test.
```
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
```
We gonna create Go module to manage its dependencies.
```
$ go mod init henry-on-the-internet.com/main
$ go mod tidy
```
We can start the API service.
` $ go run main.go`
We can test it via Postman, visiting it on browsers or curl.
http://localhost:8080/ping
---
### Containerize your API vid Docker commands
Install Docker an run it
``` $ docker run --rm -it -v `pwd`:/app -w /app -p 8080:8080 golang:1.18 go run main.go```
> `--rm` tells docker to remove this image after executing it.
> `-v` tells docker where to store the program
> `-w` tells docker where is working directory
> `-p` tells docker how to publish the port mapping
We can test it using the same methods.
---
### Create an automated build using Dockerfile
Create a file called Dockerfile in the folder main.go is inside
```
From golang:1.18
WORKDIR /go/src/app
COPY . .
RUN go build -o main main.go
CMD ["./main"]
```
Build and run it via commands
```
$ docker build -t myapp .
$ docker run --rm -p 8080:8080 myapp
```
Note: Remember do not configure our API to listen the port only on localhost `r.Run(localhost:8080)`
It is not reachable when we dockerizer it. We can find the IP address using the following command.
```
$ docker ps
0.0.0.0:8080->8080/tcp, :::8080->8080/tcp
```