Simple Golang API with Gorm and Postgres
git clone https://github.com/roalcantara/goapi.git
-
Run
go run main.go
-
Build
docker compose build --remove-orphans
-
Run
docker compose up --remove-orphans
-
Build and Run
docker compose up --build --remove-orphans
-
Shutdown
docker compose down --remove-orphans
-
docker run -it --rm -v $PWD:/app --workdir="/app" golang:1.19 sh
go mod init github.com/roalcantara/api
go get github.com/githubnemo/CompileDaemon
go install github.com/githubnemo/CompileDaemon
go get github.com/joho/godotenv
go get -u github.com/gin-gonic/gin
go get -u gorm.io/gorm
gorm.io/driver/postgres
-
touch .env
PORT=3000 POSTGRES_HOST=db POSTGRES_USER=postgres POSTGRES_PASSWORD=postgres POSTGRES_DB=postgres POSTGRES_PORT=5432
-
touch main.go
// main.go package main import ( "log" "github.com/gin-gonic/gin" "github.com/joho/godotenv" ) func init() { err := godotenv.Load() if err != nil { log.Fatal("Error loading .env file") } } func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "Hello World!", }) }) r.Run() }
-
touch Dockerfile
# Dockerfile FROM golang:1.19-alpine as build WORKDIR /app COPY . . RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o api FROM gcr.io/distroless/static:latest as prod WORKDIR /app COPY --from=build /app/api /bin ENTRYPOINT [ "/bin" ] FROM golang:1.19-alpine as dev WORKDIR /app COPY . . RUN go install -mod=mod github.com/githubnemo/CompileDaemon ENTRYPOINT CompileDaemon --build="go build main.go" --command="./main" FROM golang:1.19-alpine as test COPY --from=build /app/api /bin RUN go test
-
touch docker-compose.yml
version: '3.9' services: db: image: postgres:alpine restart: always env_file: .env ports: - 5432:5432 volumes: - postgresqldb:/var/lib/postgresql/data api: depends_on: - db build: context: . target: dev restart: unless-stopped env_file: .env environment: - DB_HOST=db - DB_USER=$POSTGRES_USER - DB_PASSWORD=$POSTGRES_PASSWORD - DB_NAME=$POSTGRES_DB - DB_PORT=$POSTGRES_PORT expose: - 3001 ports: - 3001:3001 volumes: - .:/app stdin_open: true tty: true volumes: postgresqldb: driver: local
-
docker compose up --build
-
curl http://localhost:3001
- Bug reports and pull requests are welcome on GitHub
- Do follow Editor Config rules.
- Do follow Git lint rules.
- Everyone interacting in the project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the Contributor Covenant code of conduct.
The project is available as open source under the terms of the MIT License