|
| 1 | +package main |
| 2 | + |
| 3 | +// TinyGo wasm module |
| 4 | +import ( |
| 5 | + hf "github.com/bots-garden/capsule/capsulemodule/hostfunctions" |
| 6 | + /* string to json */ |
| 7 | + "github.com/tidwall/gjson" |
| 8 | + /* create json string */ |
| 9 | + "github.com/tidwall/sjson" |
| 10 | +) |
| 11 | + |
| 12 | +// main is required. |
| 13 | +func main() { |
| 14 | + |
| 15 | + hf.SetHandleHttp(Handle) |
| 16 | +} |
| 17 | + |
| 18 | +func Handle(bodyReq string, headersReq map[string]string) (bodyResp string, headersResp map[string]string, errResp error) { |
| 19 | + /* |
| 20 | + bodyReq = {"author":"Philippe","message":"Golang 💚 wasm"} |
| 21 | + */ |
| 22 | + hf.Log("📝 body: " + bodyReq) |
| 23 | + |
| 24 | + author := gjson.Get(bodyReq, "author") |
| 25 | + message := gjson.Get(bodyReq, "message") |
| 26 | + hf.Log("👋 " + message.String() + " by " + author.String() + " 😄") |
| 27 | + |
| 28 | + hf.Log("Content-Type: " + headersReq["Content-Type"]) |
| 29 | + hf.Log("Content-Length: " + headersReq["Content-Length"]) |
| 30 | + hf.Log("User-Agent: " + headersReq["User-Agent"]) |
| 31 | + |
| 32 | + envMessage, err := hf.GetEnv("MESSAGE") |
| 33 | + if err != nil { |
| 34 | + hf.Log("😡 " + err.Error()) |
| 35 | + } else { |
| 36 | + hf.Log("Environment variable: " + envMessage) |
| 37 | + } |
| 38 | + |
| 39 | + headersResp = map[string]string{ |
| 40 | + "Content-Type": "application/json; charset=utf-8", |
| 41 | + "Message": "👋 hello world 🌍", |
| 42 | + } |
| 43 | + |
| 44 | + jsondoc := `{"message": "", "author": ""}` |
| 45 | + jsondoc, _ = sjson.Set(jsondoc, "message", "👋 Hello! What's up?") |
| 46 | + jsondoc, _ = sjson.Set(jsondoc, "author", "Bob") |
| 47 | + |
| 48 | + return jsondoc, headersResp, nil |
| 49 | + //return jsondoc, headersResp , errors.New("😡 oups I did it again") |
| 50 | +} |
| 51 | + |
| 52 | +// TODO: helpers: SetHeader() ... |
| 53 | +// TODO: be able to return a status code |
| 54 | + |
| 55 | +/* |
| 56 | +curl -v -X POST \ |
| 57 | + http://localhost:9091 \ |
| 58 | + -H 'content-type: application/json' \ |
| 59 | + -d '{"message": "Golang 💚 wasm"}' |
| 60 | +*/ |
0 commit comments