Skip to content

Commit f4e8002

Browse files
authored
added go bindgen readme (#510)
Signed-off-by: Jiaxiao Zhou <jiazho@microsoft.com>
1 parent 16994da commit f4e8002

File tree

1 file changed

+55
-5
lines changed

1 file changed

+55
-5
lines changed

README.md

Lines changed: 55 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -296,11 +296,61 @@ e.g. Java, Kotlin, Clojure, Scala, etc.
296296

297297
### Guest: TinyGo
298298

299-
The Go language currently can be compiled to standalone out-of-browser
300-
WebAssembly binaries using the [TinyGo](https://tinygo.org/) toolchain.
301-
Support does not yet exist in this repository for TinyGo but is being worked on
302-
[in a PR](https://github.com/bytecodealliance/wit-bindgen/pull/321) and is
303-
expected to land in this repository at some point in the future.
299+
Go code can be compiled for the `wasm32-wasi` target using the [TinyGo](https://tinygo.org/) compiler. For example, the following command compiles `main.go` to a wasm modules with WASI support:
300+
301+
`tinygo build -target -target=wasi main.go`
302+
303+
> Note: the current TinyGo bindgen only supports TinyGo version v0.27.0 or later.
304+
305+
To start in Go a `*.go` and `*.h` C header file are generated for your
306+
project to use. These files are generated with the [`wit-bindgen` CLI
307+
command][cli-install] in this repository.
308+
309+
```sh
310+
wit-bindgen tiny-go ./wit
311+
# Generating "host.go"
312+
# Generating "host.c"
313+
# Generating "host.h"
314+
# Generating "host_component_type.o"
315+
```
316+
317+
If your Go code uses `result` or `option` type, a second Go file `host_types.go` will be generated. This file contains the Go types that correspond to the `result` and `option` types in the WIT file.
318+
319+
Some example code using this would then look like
320+
321+
```go
322+
// my-component.go
323+
package main
324+
325+
import (
326+
gen "host/gen"
327+
)
328+
329+
func init() {
330+
a := HostImpl{}
331+
gen.SetHost(a)
332+
}
333+
334+
type HostImpl struct {
335+
}
336+
337+
func (e HostImpl) Run() {
338+
gen.Print("Hello, world!")
339+
}
340+
341+
//go:generate wit-bindgen tiny-go ../wit --out-dir=gen
342+
func main() {}
343+
```
344+
345+
This can then be compiled with `tinygo` and assembled into a component with:
346+
347+
```sh
348+
go generate # generate bindings for Go
349+
tinygo build -target=wasi --out main.wasm my-component.go # compile
350+
wasm-tools component embed --world world ./wit main.wasm > main.embed.wasm # create a component
351+
wasm-tools component new main.embed.wasm -o main.component.wasm
352+
wasm-tools validate main.component.wasm --features component-model
353+
```
304354

305355
### Guest: Other Languages
306356

0 commit comments

Comments
 (0)