We at e.GO Mobile developing tools and microservices in Go (but not only).

One of these Go tools is the open source app e.GPT, a CLI tool by e.GO, which provides different tools for OpenAI’s ChatGPT API, like translation of texts, creating shell commands from natural language or explaining source code.

Another nice feature is, that it provides a web UI that is very similar to ChatGPT.

This time I will explain how you can embed a Single Page Application (SPA) with a Go app.

Demo

A corresponding demo project can be found on GitHub as usual.

UI

The UI in the demo is implemented with Vuetify and can be found in ui-dev/ subfolder.

You can use any other framework, but at the end all final files have to be stored inside ui/ subfolder, which has to be inside the root directory and should provide at least one index.html file in this folder.

How it works

Up-to-date Go compilers can make use of the embed package.

It provides a directive, which is called //go:embed

With it, you are able to embed files into your final binary and access them as a “real” file-system at runtime:

// ...

import (
	"embed"
	
    // ...
)

//go:embed ui/*
var webUI embed.FS

/// ...

Fortunately, the http package of Go already provides a factory function to handle these files as “real” file system elements:

// ...

// this will provide all files into `ui/` subfolder
http.Handle(
    "/ui/",
    http.FileServer(
        http.FS(webUI),
    ),
)

// ...

Build & run

To make it much easier, I implemented npm run dev and npm run build scripts in package.json, which requires a installed Node.js compatible runtime as well.

Conclusion & outlook

Pretty simple, isn’t it? 😎

In one of the next posts, I will show you how to implement this in a way that the projects are automatically reloaded when there is any change in the source code (I have already written an article about something like this in this previuos post).

Happy coding! 🎉