Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding files via relative paths in go

Tags:

go

I have this file structure:

lib/ 
  util.go
CHANGELOG.md

In util.go I need to embed CHANGELOG.md. I try:

//go:embed ../CHANGELOG.md
var changelog string

But I get this error: pattern ../CHANGELOG.md: invalid pattern syntax

If I can't embed resources via relative paths, what are the best practices for embedding resources in sub-modules?

like image 819
Andrey Avatar asked Dec 22 '25 15:12

Andrey


2 Answers

according embed docs:

The patterns are interpreted relative to the package directory containing the source file. The path separator is a forward slash, even on Windows systems. Patterns may not contain ā€˜.’ or ā€˜..’ or empty path elements, nor may they begin or end with a slash.

This means that the root of the relative path is the folder where the go sources files are located. So I think we couldn't embedding resources from other local folders.

Maybe this comment can explain why it's designed like this, and this answer provide a solution.

If there is an error, please advise. šŸŽ‰

like image 76
Macondo Avatar answered Dec 24 '25 05:12

Macondo


you can add a embed.go file

embed.go

package project-root

import "embed"

//go:embed CHANGELOG.md
var Changelog string

util.go

func main() {
   log := project-root.Changelog
}

Project Structure

project-root/
ā”œā”€ā”€ lib/
│   ā”œā”€ā”€ util.go
ā”œā”€ā”€ CHANGELOG.md
ā”œā”€ā”€ embed.go

like image 24
zhangwt Avatar answered Dec 24 '25 04:12

zhangwt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!