Replies: 2 comments
-
How to send an http request in tinygo? |
Beta Was this translation helpful? Give feedback.
0 replies
-
To implement a basic authentication plug-in using TinyGo and Redis based on WebAssembly, follow these steps:
Here is an example: package main
import (
"github.com/tetratelabs/proxy-wasm-go-sdk/proxywasm"
"github.com/tetratelabs/proxy-wasm-go-sdk/proxywasm/types"
)
func main() {
proxywasm.SetVMContext(&vmContext{})
}
type vmContext struct {
types.DefaultVMContext
}
func (*vmContext) NewPluginContext(contextID uint32) types.PluginContext {
return &pluginContext{}
}
type pluginContext struct {
types.DefaultPluginContext
}
func (ctx *pluginContext) NewHttpContext(contextID uint32) types.HttpContext {
return &httpContext{}
}
type httpContext struct {
types.DefaultHttpContext
}
func (ctx *httpContext) OnHttpRequestHeaders(numHeaders int, endOfStream bool) types.Action {
// Extract credentials from headers
authHeader, err := proxywasm.GetHttpRequestHeader("Authorization")
if err != nil {
proxywasm.LogErrorf("failed to get Authorization header: %v", err)
return types.ActionContinue
}
// Make an HTTP call to the authentication service
_, err = proxywasm.DispatchHttpCall("auth_service_cluster",
[][2]string{
{"Authorization", authHeader},
},
nil, nil, 5000, // 5 seconds timeout
func(numHeaders, bodySize, numTrailers int) {
// Handle the response from the authentication service
status, err := proxywasm.GetHttpCallResponseStatus()
if err != nil {
proxywasm.LogErrorf("failed to get response status: %v", err)
return
}
if status != 200 {
// Authentication failed
proxywasm.SendHttpResponse(401, nil, []byte("Unauthorized"), -1)
} else {
// Authentication succeeded
proxywasm.ContinueRequest()
}
})
if err != nil {
proxywasm.LogErrorf("failed to dispatch HTTP call: %v", err)
return types.ActionContinue
}
return types.ActionPause
}
tinygo build -o auth_plugin.wasm -scheduler=none -target=wasi ./main.go
wasm:
plugins:
- name: auth_plugin
priority: 1000
file: /opt/apisix/wasm/auth_plugin.wasm
curl http://127.0.0.1:9180/apisix/admin/routes/1 \
-H 'X-API-KEY: your-api-key' -X PUT -d '{
"uri": "/*",
"upstream": {
"type": "roundrobin",
"nodes": {
"your-upstream-service:80": 1
}
},
"plugins": {
"auth_plugin": {}
}
}' This setup will allow you to use TinyGo and Redis to implement a basic authentication plug-in based on WebAssembly, and TinyGo will invoke an HTTP service for the authentication [1][2]. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
The authentication service can use an http service. How does tinygo invoke it?
Beta Was this translation helpful? Give feedback.
All reactions