navidrome/plugins/cmd/hostgen/testdata/math_expected.go
Deluan cab656dbe5 refactor: host function wrappers to use structured request and response types
- Updated the host function signatures in `nd_host_artwork.go`, `nd_host_scheduler.go`, `nd_host_subsonicapi.go`, and `nd_host_websocket.go` to accept a single parameter for JSON requests.
- Introduced structured request and response types for various cache operations in `nd_host_cache.go`.
- Modified cache functions to marshal requests to JSON and unmarshal responses, improving error handling and code clarity.
- Removed redundant memory allocation for string parameters in favor of JSON marshaling.
- Enhanced error handling in WebSocket and cache operations to return structured error responses.
2025-12-31 17:06:29 -05:00

90 lines
2.2 KiB
Go

// Code generated by hostgen. DO NOT EDIT.
package testpkg
import (
"context"
"encoding/json"
extism "github.com/extism/go-sdk"
)
// MathAddRequest is the request type for Math.Add.
type MathAddRequest struct {
A int32 `json:"a"`
B int32 `json:"b"`
}
// MathAddResponse is the response type for Math.Add.
type MathAddResponse struct {
Result int32 `json:"result,omitempty"`
Error string `json:"error,omitempty"`
}
// RegisterMathHostFunctions registers Math service host functions.
// The returned host functions should be added to the plugin's configuration.
func RegisterMathHostFunctions(service MathService) []extism.HostFunction {
return []extism.HostFunction{
newMathAddHostFunction(service),
}
}
func newMathAddHostFunction(service MathService) extism.HostFunction {
return extism.NewHostFunctionWithStack(
"math_add",
func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
// Read JSON request from plugin memory
reqBytes, err := p.ReadBytes(stack[0])
if err != nil {
mathWriteError(p, stack, err)
return
}
var req MathAddRequest
if err := json.Unmarshal(reqBytes, &req); err != nil {
mathWriteError(p, stack, err)
return
}
// Call the service method
result, svcErr := service.Add(ctx, req.A, req.B)
if svcErr != nil {
mathWriteError(p, stack, svcErr)
return
}
// Write JSON response to plugin memory
resp := MathAddResponse{
Result: result,
}
mathWriteResponse(p, stack, resp)
},
[]extism.ValueType{extism.ValueTypePTR},
[]extism.ValueType{extism.ValueTypePTR},
)
}
// mathWriteResponse writes a JSON response to plugin memory.
func mathWriteResponse(p *extism.CurrentPlugin, stack []uint64, resp any) {
respBytes, err := json.Marshal(resp)
if err != nil {
mathWriteError(p, stack, err)
return
}
respPtr, err := p.WriteBytes(respBytes)
if err != nil {
stack[0] = 0
return
}
stack[0] = respPtr
}
// mathWriteError writes an error response to plugin memory.
func mathWriteError(p *extism.CurrentPlugin, stack []uint64, err error) {
errResp := struct {
Error string `json:"error"`
}{Error: err.Error()}
respBytes, _ := json.Marshal(errResp)
respPtr, _ := p.WriteBytes(respBytes)
stack[0] = respPtr
}