Portable apps with Go and Next.js

submited by
Style Pass
2021-06-12 23:30:03

The release of Go 1.16 introduced a new embed package in the Go standard library. It provides access to files embedded in a Go program at compile time using the new //go:embed directive. It’s a powerful new feature because it allows building a binary with static dependencies like templates, HTML/CSS/JS, or images self-contained. This portability is great for easy distribution and usage. Previously, developers had to rely on third-party libraries for embed behaviour.

In this article we’ll walk through a small demo app, golang-nextjs-portable, that exposes an HTTP server that hosts both an API endpoint, as well as an embedded (Next.js) web app that calls the API.

An interesting use case for the embed package is bundling a web UI in your Go program. A web frontend can have some advantages over a terminal-based UI (TUI). For example, you can run the HTTP server in your home network, and access it from any browser across (mobile) devices. It can also empower you to build user-friendly UI/UX, leveraging web technologies that browsers natively support. When building a hybrid between offline/self-hosted and SaaS, it makes it possible to reuse the same code across self-contained binaries (e.g. for IoT or Raspberry Pi devices) and a hosted/SaaS platform.

It uses the http package to run a simple HTTP web server on port :8080. The API is served under /api and returns a text response with current memory allocation stats.

Leave a Comment