SoFunction
Updated on 2025-04-14

How to package jar application using Golang

background

Want to package one of your SpringBoot applications into executable files. See how Golang does it.

Go's go:embed function introduction and packaging JAR file examples

go:embedis a powerful feature introduced in Go 1.16, which allows external files or directories to be embedded into Go programs at compile time. Here is how to use itgo:embedto embed the JAR file.

1. go:embed Basic introduction

Basic Features

  • Embed file contents at compile time
  • Supports embedding of single files, multiple files, or entire directories
  • Three embedding types are supported:
    • string- Used for text files
    • []byte- For binary files
    • - Used for file system (supports multiple files/directories)

Basic syntax

import "embed"
//go:embed 
var fileContent string
//go:embed 
var imageData []byte
//go:embed templates/*
var templatesFS 

2. Embed JAR file example

Suppose you have one that needs to be embeddedFile, the following is the complete example:

Project structure

project/
├── embedded/
│   └──     # JAR file to be embedded├── 
└── 

Code implementation

package main
import (
	"embed"
	"io"
	"log"
	"os"
	"path/filepath"
)
//go:embed embedded/
var jarFile []byte
func main() {
	// Specify the output path (can be temporary directory or specific location)	outputPath := ((), "")
	// Write embedded JAR to file system	err := (outputPath, jarFile, 0755)
	if err != nil {
		("Failed to write JAR file: %v", err)
	}
	("JAR file extracted to: %s", outputPath)
	// Now you can use this JAR file, for example by running it	// ("java", "-jar", outputPath)
}

3. Advanced usage: Embed multiple files or directories

If you have multiple JAR files that need to be embedded:

//go:embed embedded/*.jar
var jarFiles 
func main() {
	// List all embedded JAR files	entries, err := ("embedded")
	if err != nil {
		(err)
	}
	// Extract all JAR files	for _, entry := range entries {
		if (()) == ".jar" {
			data, err := ("embedded/" + ())
			if err != nil {
				("Failed to read %s: %v", (), err)
				continue
			}
			outputPath := ((), ())
			err = (outputPath, data, 0755)
			if err != nil {
				("Failed to write %s: %v", (), err)
				continue
			}
			("Extracted %s to %s", (), outputPath)
		}
	}
}

4. Precautions for use

Path rules

  • go:embedThe path is relative to the Go source file containing the instruction
  • Cannot include.or..Equal path components
  • Cannot match files in parent directory

File size limit

  • Go 1.16+ has no hard limit on embedded file size
  • But very large files may increase compile time and binary size

Build constraints

  • The embedded file must be available at build time
  • If the file does not exist, the build will fail

Safety considerations

  • Pay attention to the permissions of the target path when extracting embedded files
  • Consider using a temporary directory and clean it up when the program exits

5. Practical application scenarios

  • Packaging Java applications: Embed the dependency JAR file into the Go program and then passCall Java to run
  • Embedded database: Such as SQLite database file
  • Web server resources: HTML/CSS/JS and other front-end resources
  • Configuration File: Default configuration template

6. Complete example: Running an embedded JAR

package main
import (
	"embed"
	"log"
	"os"
	"os/exec"
	"path/filepath"
)
//go:embed 
var jarFile []byte
func main() {
	// Create temporary files	tmpFile, err := ("", "embedded-*.jar")
	if err != nil {
		(err)
	}
	defer (()) // Delete when the program exits	// Write JAR content	if _, err := (jarFile); err != nil {
		(err)
	}
	if err := (); err != nil {
		(err)
	}
	// Execute Java commands	cmd := ("java", "-jar", ())
	 = 
	 = 
	("Starting Java application...")
	if err := (); err != nil {
		("Java application failed: %v", err)
	}
}

This way you can package your Java application into a Go binary and then distribute and start it through a Go program.

This is all about this article about using Golang to package jar applications. For more related content on Golang to package jar applications, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!