- Compile - basics of how to compile and execute a basic program and other common tools
- Modules - how to create a reusable module in the local project. How to mange exports and imports into a consuming module.
- Import Package - how add an external package to a program and import it. How to upgrade to new revisions and lock to a specific version.
- Publish a Package - how to author and publish a package for external consumption
- Tests - how to add tests to a package that can be run as part of CI/CD
- Custom Tools - how to incorporate custom tools as part of the build process (e.g. openapi code generation)
Package Deployment
Change TopicGo Package Deployment
TypeScript Package and Deploy
Compile
To compile and execute a basic Go program, use the go build
and go run
commands Example: Basic Go Compilation:
// main.go package main import "fmt" func main() { fmt.Println("Hello, Go!") }
To compile and run:
go build -o myprogram main.go ./myprogram
Alternatively, you can directly execute the Go program without compiling:
go run main.go
Common Compilation Tools:
go fmt
– Formats Go code according to Go standards.go vet
– Analyzes code for potential issues.golint
– Provides stylistic recommendations.
go fmt main.go go vet main.go golint main.go
Compile
To compile a TypeScript program, install the TypeScript compiler:
npm install -g typescript
Create a simple index.ts
file:
const message: string = "Hello, TypeScript!"; console.log(message);
Compile the file:
tsc index.ts
This generates an index.js
file that can be executed with Node.js:
node index.js
Modules
Creating a Reusable Module: Go modules allow you to manage dependencies and organize reusable code.
Initialize a Module:
go mod init example.com/mymodule
This creates a go.mod
file:
module example.com/mymodule go 1.20
To defining an Exported Function:
// mymodule/mylib.go package mymodule import "fmt" // Exported function (must start with uppercase letter) func SayHello(name string) { fmt.Printf("Hello, %s!\n", name) }
Using the Module in Another File:
package main import ( "example.com/mymodule" ) func main() { mymodule.SayHello("Alice") }
Managing Dependencies:
- Add a dependency:
go get example.com/somepackage
- Remove unused dependencies:
go mod tidy
- List dependencies:
go list -m all
Modules
Create a module in math.ts
:
export function add(a: number, b: number): number { return a + b; }
Consume it in index.ts
:
import { add } from "./math"; console.log(add(2, 3));
Compile and run:
tsc && node index.js
Import Package
To add an External Package. Use go get
to install third-party packages.
Example: Using github.com/fatih/color
for Colored Output:
go get github.com/fatih/color
Import and use it:
package main import ( "github.com/fatih/color" ) func main() { color.Red("This is a red message") }
Upgrading a Package:
go get -u github.com/fatih/color
Locking to a Specific Version:
go get github.com/fatih/color@v1.12.0
Checking and Managing Dependencies:
Go provides mechanisms to lock dependencies to specific versions and ensure reproducible builds.
Generating and Committing a Lockfile - Go automatically maintains a go.sum
file, which records cryptographic checksums of dependencies. This file should be committed to version control to ensure consistency across builds.
git add go.sum git commit -m "Add go.sum to track dependency checksums"
Checking Installed Modules:
go list -m all # List all modules in use
Tidying Dependencies:
go mod tidy # Remove unused dependencies and update go.mod and go.sum
Verifying Module Integrity:
go mod verify # Verify checksums in go.sum against downloaded modules
go list -m all # List all modules go mod tidy # Remove unused dependencies go mod verify # Verify checksums
Import Package
To add an external package, use npm:
npm install lodash
Import and use it in index.ts
:
import _ from "lodash"; console.log(_.capitalize("hello world"));
Lock to a specific version:
npm install lodash@4.17.21
Upgrade a package:
npm update lodash
Publish a Package
Publishing a Go Package for External Use. To publish a package:
- Create a public repository on GitHub/GitLab.
- Ensure a valid
go.mod
file. - Push the module to a repository.
git init git remote add origin https://github.com/username/mymodule.git git add . git commit -m "Initial commit" git push -u origin main
Tagging a Release:
git tag v1.0.0 git push origin v1.0.0
Using the Published Module:
go get github.com/username/mymodule@v1.0.0
Example: Importing and Using the Published Module:
package main import ( "github.com/username/mymodule" ) func main() { mymodule.SayHello("Bob") }
Publish a Package
-
Initialize a package:
npm init -y
-
Add TypeScript support:
npm install typescript --save-dev
-
Write a module in
index.ts
:export function greet(name: string): string { return `Hello, ${name}!`; }
-
Configure
package.json
:"main": "dist/index.js", "types": "dist/index.d.ts",
-
Publish:
npm login npm publish
Tests
Adding Tests to a Package. Go includes a built-in testing
package for unit testing. Example: Writing a Test:
// mymodule/mylib.go package mymodule func Add(a, b int) int { return a + b }
// mymodule/mylib_test.go package mymodule import "testing" func TestAdd(t *testing.T) { result := Add(2, 3) expected := 5 if result != expected { t.Errorf("Expected %d but got %d", expected, result) } }
Running Tests:
go test ./...
Running Tests with Coverage:
go test -cover ./...
Integrating Tests into CI/CD. To automate testing in CI pipelines, add:
go test ./... && go vet ./...
to your build pipeline configuration.
Tests
Install a test framework:
npm install --save-dev jest @types/jest ts-jest
Configure Jest in jest.config.js
:
module.exports = { preset: "ts-jest", testEnvironment: "node", };
Create math.test.ts
:
import { add } from "./math"; test("adds 1 + 2 to equal 3", () => { expect(add(1, 2)).toBe(3); });
Run tests:
npm test
Custom Tools
Incorporating Code Generation Tools. Some Go projects require automatic code generation, such as OpenAPI or gRPC.
Installing stringer
for Enum String Generation
go install golang.org/x/tools/cmd/stringer@latest
Using it in Go:
// Define an enum package main //go:generate stringer -type=Animal type Animal int const ( Dog Animal = iota Cat Fish )
Generate code:
go generate ./...
Generating OpenAPI with oapi-codegen
:
go install github.com/deepmap/oapi-codegen/cmd/oapi-codegen@latest oapi-codegen -generate types -o types.gen.go api.yaml
Automating Builds with a Custom Script. Example build.sh
script:
#!/bin/bash set -e go fmt ./... go vet ./... go test ./... go build -o myapp main.go echo "Build successful!"
Run:
chmod +x build.sh ./build.sh
Custom Tools
Example: OpenAPI code generation
-
Install OpenAPI generator:
npm install @openapitools/openapi-generator-cli -g
-
Generate TypeScript client:
openapi-generator-cli generate -i openapi.yaml -g typescript-fetch -o generated-client
-
Use it in a project:
import { ApiClient } from "./generated-client"; const client = new ApiClient();