Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Go #129

Merged
merged 8 commits into from
May 30, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
59 changes: 59 additions & 0 deletions examples/go-basic/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package main

import (
"fmt"
"io"
"net/http"

"github.com/vmware-labs/wasm-workers-server/kits/go/worker"
)

func main() {
worker.ServeFunc(func(w http.ResponseWriter, r *http.Request) {
var payload string

reqBody, err := io.ReadAll(r.Body)
if err != nil {
panic(err)
}
r.Body.Close()

if len(reqBody) == 0 {
payload = "-"
} else {
payload = string(reqBody)
}

body := fmt.Sprintf("<!DOCTYPE html>"+
"<head>"+
"<title>Wasm Workers Server</title>"+
"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">"+
"<meta charset=\"UTF-8\">"+
"<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/water.css@2/out/water.css\">"+
"<style>"+
"body { max-width: 1000px; }"+
"main { margin: 5rem 0; }"+
"h1, p { text-align: center; }"+
"h1 { margin-bottom: 2rem; }"+
"pre { font-size: .9rem; }"+
"pre > code { padding: 2rem; }"+
"p { margin-top: 2rem; }"+
"</style>"+
"</head>"+
"<body>"+
"<main>"+
"<h1>Hello from Wasm Workers Server 👋</h1>"+
"<pre><code>Replying to %s<br>"+
"Method: %s<br>"+
"User Agent: %s<br>"+
"Payload: %s</code></pre>"+
"<p>"+
"This page was generated by a Go file running in WebAssembly."+
"</p>"+
"</main>"+
"</body>", r.URL.String(), r.Method, r.UserAgent(), payload)

w.Header().Set("x-generated-by", "wasm-workers-server")
w.Write([]byte(body))
})
}
18 changes: 18 additions & 0 deletions examples/go-envs/envs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package main

import (
"fmt"
"net/http"
"os"

"github.com/vmware-labs/wasm-workers-server/kits/go/worker"
)

func main() {
worker.ServeFunc(func(w http.ResponseWriter, r *http.Request) {
body := fmt.Sprintf("The environment variable value is: %s", os.Getenv("MESSAGE"))

w.Header().Set("x-generated-by", "wasm-workers-server")
w.Write([]byte(body))
})
}
5 changes: 5 additions & 0 deletions examples/go-envs/envs.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
name = "envs"
version = "1"

[vars]
MESSAGE = "Hello! This message comes from an environment variable"
34 changes: 34 additions & 0 deletions examples/go-kv/counter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package main

import (
"fmt"
"net/http"
"strconv"

"github.com/vmware-labs/wasm-workers-server/kits/go/worker"
)

func main() {
worker.ServeFunc(func(w http.ResponseWriter, r *http.Request) {
cache, _ := r.Context().Value("CACHE").(map[string]string)

var countNum uint32

if count, ok := cache["counter"]; ok {
n, _ := strconv.ParseUint(count, 10, 32)
countNum = uint32(n)
}

body := fmt.Sprintf("<!DOCTYPE html>"+
"<body>"+
"<h1>Key / Value store in Go</h1>"+
"<p>Counter: %d</p>"+
"<p>This page was generated by a Wasm modules built from Go.</p>"+
"</body>", countNum)

cache["counter"] = fmt.Sprintf("%d", countNum+1)

w.Header().Set("x-generated-by", "wasm-workers-server")
w.Write([]byte(body))
})
}
6 changes: 6 additions & 0 deletions examples/go-kv/counter.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
name = "counter"
version = "1"

[data]
[data.kv]
namespace = "counter"
41 changes: 41 additions & 0 deletions examples/go-params/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package main

import (
"fmt"
"net/http"

"github.com/vmware-labs/wasm-workers-server/kits/go/worker"
)

func main() {
worker.ServeFunc(func(w http.ResponseWriter, r *http.Request) {
params, _ := r.Context().Value("PARAMS").(map[string]string)
id := "the value is not available"

if val, ok := params["id"]; ok {
id = val
}

body := fmt.Sprintf("<!DOCTYPE html>"+
"<head>"+
"<title>Wasm Workers Server</title>"+
"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">"+
"<meta charset=\"UTF-8\">"+
"<link rel=\"stylesheet\" href=\"/water.min.css\">"+
"<link rel=\"stylesheet\" href=\"/main.css\">"+
"</head>"+
"<body>"+
"<main>"+
"<h1>Hello from Wasm Workers Server 👋</h1>"+
"<p>"+
"This is a dynamic route! The <code>[id].wasm</code> worker, written in Go, is replying this URL."+
"The <code>id</code> parameter value is: <code>%s</code>"+
"</p>"+
"<p>Read more about dynamic routes <a href=\"https://workers.wasmlabs.dev/docs/features/dynamic-routes\">in the documentation</a></p>"+
"</main>"+
"</body>", id)

w.Header().Set("x-generated-by", "wasm-workers-server")
w.Write([]byte(body))
})
}
28 changes: 28 additions & 0 deletions examples/go-params/public/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
body {
max-width: 1000px;
}

main {
margin: 5rem 0;
}

h1,
p {
text-align: center;
}

h1 {
margin-bottom: 2rem;
}

pre {
font-size: .9rem;
}

pre>code {
padding: 2rem;
}

p {
margin-top: 2rem;
}
30 changes: 30 additions & 0 deletions examples/go-params/public/water.min.css

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module github.com/vmware-labs/wasm-workers-server

go 1.20

require github.com/tidwall/gjson v1.14.4

require (
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
)
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
github.com/tidwall/gjson v1.14.4 h1:uo0p8EbA09J7RQaflQ1aBRffTR7xedD2bcIVSYxLnkM=
github.com/tidwall/gjson v1.14.4/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
163 changes: 163 additions & 0 deletions kits/go/worker/worker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
package worker

import (
"context"
"encoding/base64"
"fmt"
"io"
"net/http"
"os"
"strings"
"unicode/utf8"

"github.com/tidwall/gjson"
)

var cache map[string]string

func init() {
cache = make(map[string]string)
}

type input struct {
url string
method string
headers map[string]string
body string
params map[string]string
}

type output struct {
data string
headers map[string]string
status uint16
kv map[string]string
base64 bool

httpHeader http.Header
}

func (o *output) Header() http.Header {
if o.httpHeader == nil {
o.httpHeader = http.Header{}
}

return o.httpHeader
}

func (o *output) Write(data []byte) (int, error) {
if utf8.Valid(data) {
o.data = string(data)
} else {
o.base64 = true
o.data = base64.StdEncoding.EncodeToString(data)
}

if o.status == 0 {
o.status = 200
}

for k, v := range o.httpHeader {
o.headers[k] = v[0]
}

headersOut := "{"

for k, v := range o.headers {
headersOut += fmt.Sprintf(`"%s":"%s",`, k, v)
}

headersOut = strings.TrimSuffix(headersOut, ",") + "}"

kvOut := "{"

for k, v := range cache {
kvOut += fmt.Sprintf(`"%s":"%s",`, k, v)
}

kvOut = strings.TrimSuffix(kvOut, ",") + "}"

fmt.Printf("{\"data\":\"%s\",\"headers\":%s,\"status\":%d,\"kv\":%s,\"base64\":%t}",
strings.ReplaceAll(o.data, "\"", "\\\""), headersOut, o.status, kvOut, o.base64)
Angelmmiguel marked this conversation as resolved.
Show resolved Hide resolved

return len(o.data), nil
}

func (o *output) WriteHeader(statusCode int) {
o.status = uint16(statusCode)
}
Angelmmiguel marked this conversation as resolved.
Show resolved Hide resolved

func readInput() *input {
stdin, err := io.ReadAll(os.Stdin)
if err != nil {
panic(err)
}

in := &input{
url: gjson.GetBytes(stdin, "url").String(),
method: gjson.GetBytes(stdin, "method").String(),
body: gjson.GetBytes(stdin, "body").String(),
}

if gjson.GetBytes(stdin, "headers").Exists() {
in.headers = make(map[string]string)

gjson.GetBytes(stdin, "headers").ForEach(func(key, value gjson.Result) bool {
in.headers[key.String()] = value.String()
return true
})
}

if gjson.GetBytes(stdin, "kv").Exists() {
gjson.GetBytes(stdin, "kv").ForEach(func(key, value gjson.Result) bool {
cache[key.String()] = value.String()
return true
})
}

if gjson.GetBytes(stdin, "params").Exists() {
in.params = make(map[string]string)

gjson.GetBytes(stdin, "params").ForEach(func(key, value gjson.Result) bool {
in.params[key.String()] = value.String()
return true
})
}

return in
}

func createRequest(in *input) *http.Request {
req, err := http.NewRequest(in.method, in.url, strings.NewReader(in.body))
if err != nil {
panic(err)
}

for k, v := range in.headers {
req.Header.Set(k, v)
}

req = req.WithContext(context.WithValue(req.Context(), "CACHE", cache))
req = req.WithContext(context.WithValue(req.Context(), "PARAMS", in.params))

return req
}

func getWriterRequest() (*output, *http.Request) {
in := readInput()
req := createRequest(in)
w := &output{
headers: make(map[string]string),
kv: make(map[string]string),
}

return w, req
}

func Serve(handler http.Handler) {
handler.ServeHTTP(getWriterRequest())
}

func ServeFunc(handler http.HandlerFunc) {
handler(getWriterRequest())
}