Implement basic JsonRPC Handler

This commit is contained in:
Samuel Lorch 2023-03-05 18:57:43 +01:00
parent e36af35aad
commit 503464dbf1
8 changed files with 256 additions and 2 deletions

View file

@ -1,7 +1,22 @@
package server
import "net/http"
import (
"context"
"fmt"
"net/http"
"runtime/debug"
"golang.org/x/exp/slog"
)
func HandleAPI(w http.ResponseWriter, r *http.Request) {
defer func() {
if r := recover(); r != nil {
slog.Error("Recovered Panic Handling HTTP API Request", fmt.Errorf("%v", r), "stack", debug.Stack())
}
}()
err := apiHandler.HandleRequest(context.TODO(), r.Body, w)
if err != nil {
slog.Error("Handling HTTP API Request", err)
}
}

35
pkg/server/jsonrpc.go Normal file
View file

@ -0,0 +1,35 @@
package server
import (
"context"
"fmt"
"nfsense.net/nfsense/pkg/jsonrpc"
)
var apiHandler jsonrpc.Handler
func init() {
apiHandler = jsonrpc.NewHandler(100 << 20)
apiHandler.Register("test", Ping{})
}
type Ping struct {
}
type PingRequest struct {
Msg string `json:"msg"`
}
type PingResponse struct {
Msg string `json:"msg"`
}
func (p Ping) Ping(ctx context.Context, req PingRequest) (*PingResponse, error) {
if req.Msg == "" {
return nil, fmt.Errorf("Message is empty")
}
return &PingResponse{
Msg: req.Msg,
}, nil
}