Skip to content

Developer Guide

First HTTP Module

Create a directory http-say-hello

mkdir http-say-hello
cd http-say-hello

Initialize a new project in http-say-hello:

go mod init http-say-hello

Install the Capsule MDK dependencies:

go get github.com/bots-garden/capsule-module-sdk

Create a new file main.go in http-say-hello:

// Package main
package main

import (
    "strconv"

    "github.com/bots-garden/capsule-module-sdk"
    "github.com/valyala/fastjson"
)

func main() {
    capsule.SetHandleHTTP(Handle)
}

// Handle function 
func Handle(param capsule.HTTPRequest) (capsule.HTTPResponse, error) {

    capsule.Print("πŸ“: " + param.Body)
    capsule.Print("πŸ” : " + param.Method)
    capsule.Print("🌍: " + param.URI)
    capsule.Print("πŸ‘’: " + param.Headers)

    var p fastjson.Parser
    jsonBody, err := p.Parse(param.Body)
    if err != nil {
        capsule.Log(err.Error())
    }
    message := string(jsonBody.GetStringBytes("name")) + " " + strconv.Itoa(jsonBody.GetInt("age"))
    capsule.Log(message)

    response := capsule.HTTPResponse{
        JSONBody: `{"message": "`+message+`"}`,
        Headers: `{"Content-Type": "application/json; charset=utf-8"}`,
        StatusCode: 200,
    }

    return response, nil
}

Build the wasm module:

tinygo build -o http-say-hello.wasm -scheduler=none --no-debug -target wasi ./main.go

Serve the module:

You need to download the last capsule-http runner: https://github.com/bots-garden/capsule/releases

./capsule-http --wasm=http-say-hello.wasm --httpPort=8080
- --wasm flag: the path to the wasm file - --httpPort flag: the HTTP port to listen on

Call the module (function):

1
2
3
curl -X POST http://localhost:8080 \
    -H 'Content-Type: application/json; charset=utf-8' \
    -d '{"name":"Bob Morane","age":42}'

output: (curl response)

{"message":"Bob Morane 42"}

output: (on the capsule-http side)

1
2
3
4
5
πŸ“: {"name":"Bob Morane","age":42}
πŸ” : POST
🌍: http://localhost:8080/
πŸ‘’: "Content-Type":"application/json; charset=utf-8","User-Agent":"curl/7.81.0","Accept":"*/*","Host":"localhost:8080","Content-Length":"30"
2023-05-06 08:55:55.717252231 +0200 CEST m=+24.164260454 : Bob Morane 42

You can find more samples on /capsule/capsule-http