test built-in rpc

This commit is contained in:
2024-09-06 21:00:08 +02:00
parent 990385b3e7
commit a0ce809869
4 changed files with 125 additions and 5 deletions

View File

@ -5,8 +5,11 @@ import (
"bytes"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"net/rpc"
"time"
)
type RequestPayload struct {
@ -54,9 +57,12 @@ func (app *Config) HandleSubmission(w http.ResponseWriter, r *http.Request) {
switch requestPayload.Action {
case "auth":
app.authenticate(w, requestPayload.Auth)
case "log":
// app.LogItem(w, requestPayload.Log)
case "logHttp": // 2729 us
app.LogItem(w, requestPayload.Log)
case "logRabbit": // 10007 us
app.logEventViaRabbit(w, requestPayload.Log)
case "logRpc": // 555 us
app.logItemViaRPC(w, requestPayload.Log)
case "mail":
app.SendMail(w, requestPayload.Mail)
default:
@ -80,6 +86,8 @@ func (app *Config) authenticate(w http.ResponseWriter, a AuthPayload) {
func (app *Config) LogItem(w http.ResponseWriter, entry LogPayload) {
log.Println(entry)
now := time.Now()
entry.Data += fmt.Sprintf("HTTP sent date %d", now.UnixMicro())
loggerService := Microservice{
Input: entry,
Addr: "http://logger-service/log",
@ -180,6 +188,8 @@ func (app *Config) callService(w http.ResponseWriter, ms Microservice) {
}
func (app *Config) logEventViaRabbit(w http.ResponseWriter, l LogPayload) {
now := time.Now()
l.Data += fmt.Sprintf("Rabbit sent date %d", now.UnixMicro())
err := app.pushToQueue(l.Name, l.Data)
if err != nil {
app.errorJSON(w, err)
@ -212,3 +222,34 @@ func (app *Config) pushToQueue(name, msg string) error {
return nil
}
type RPCPayload struct {
Name string
Data string
}
func (app *Config) logItemViaRPC(w http.ResponseWriter, l LogPayload) {
client, err := rpc.Dial("tcp", "logger-service:5001")
if err != nil {
app.errorJSON(w, err)
return
}
defer client.Close()
now := time.Now()
l.Data += fmt.Sprintf("RPC sent date %d", now.UnixMicro())
rpcPayload := RPCPayload(l)
var result string
err = client.Call("RPCServer.LogInfo", rpcPayload, &result)
if err != nil {
app.errorJSON(w, err)
return
}
var payload jsonResponse
payload.Error = false
payload.Message = "logged via RPC"
app.writeJSON(w, http.StatusOK, payload)
}