Reputation: 448
I have a Go program that uses some json files (like 15) for data. I want to compile it into a WebAssembly file.
How can I do this?
Note: I know I can just pass those json values from my JS code to WASM, but I don't want that if I can effectively bundle them with WASM.
EDIT: lastly we tried https://pkg.go.dev/embed as NobbyNobbs mentioned, and it's working perfectly.
Upvotes: 3
Views: 1180
Reputation: 1179
if you want to bundle any type of file/directory with compiled code (like binary/wasm) , there is a awesome Golang library packr . It's easy to use and when you compile the source code to binary or webassembly packr loads the file/directory and works the same way as before.
here i am using main.go
in the root directory of the project. and a directory to store json data (like /jsondata/mydata.json
)
package main
import (
"fmt"
"github.com/gobuffalo/packr/v2"
)
func main() {
box := packr.New("myBox", "./jsondata")
s, err := box.FindString("mydata.json")
if err != nil {
fmt.Println("🚀 ~ file: main.go ~ line 14 ~ funcmain ~ err : ", err)
}
fmt.Println(s)
}
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S"
}
}
}
than run the code using go run main.go
.
if you compiled it to the binary the json file ships with the binary code
go build main.go
if you compiled it to the wasm , the folder will behave the same way
GOOS=js GOARCH=wasm go build -o main.wasm main.go
use embed
library from standard library .
here i am using main.go
in the root directory of the project. and creating a file in same directory (like /sample.json
)
package main
import (
"embed"
)
//go:embed sample.json
var f embed.FS
func main(){
data, _ := f.ReadFile("sample.json")
print(string(data))
}
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S"
}
}
}
than run the code using go run main.go
.
if you compiled it to the binary the json file ships with the binary code
go build main.go
if you compiled it to the wasm , the folder will behave the same way
GOOS=js GOARCH=wasm go build -o main.wasm main.go
Upvotes: 1