First, make sure you have a Nx Workspace.
Create a new one using the following command:
yarn create nx-workspace go-playground --preset=empty --cli=nx --nx-cloud true
cd go-playground
Next, install the nx-go plugin:
yarn add -D @nx-go/nx-go
Create a new application:
nx g @nx-go/nx-go:app api
You can now run the Nx workspace commands:
This command builds the application using the go build
command, and stores the output in the dist/<app-name>/
directory.
nx build api
Lint the application using the go fmt
command.
nx lint api
Serves the application using the go run
command.
nx serve api
To run the application in watch mode you can use gow
, after installing it on your machine.
Find the key projects.<app-name>.architect.serve.options
and set the cmd
parameter to gow
, like so:
{
"projects": {
"api": {
"architect": {
"serve": {
"builder": "@nx-go/nx-go:serve",
"options": {
"cmd": "gow",
"main": "apps/api/src/main.go"
}
}
}
}
}
}
Test the application using the go test
command.
nx test api
In order to build Docker containers from the Go api inside the Nx Workspace, there are 2 base images provided:
- nxgo/base
- Node 14 on Alpine, with Go 1.13
- nxgo/cli
- Node 14 on Alpine, with Go 1.13
- @angular/cli v10
- @nrwl/cli v10
- nxpm v1
# Use nxgo/cli as the base image to do the build
FROM nxgo/cli as builder
# Create app directory
WORKDIR /workspace
# Copy package.json and the lock file
COPY package.json yarn.lock /workspace/
# Install app dependencies
RUN yarn
# Copy source files
COPY . .
# Build apps
RUN yarn build api
# This is the stage where the final production image is built
FROM golang:1.14-alpine as final
# Copy over artifacts from builder image
COPY --from=builder /workspace/dist/apps/api /workspace/api
# Set environment variables
ENV PORT=3000
ENV HOST=0.0.0.0
# Expose default port
EXPOSE 3000
# Start server
CMD [ "/workspace/api" ]
Created by Bram Borggreve.