Add rpc listener to logger service

This commit is contained in:
vinchent 2024-09-06 20:27:53 +02:00
parent 41dab037ce
commit 990385b3e7
2 changed files with 59 additions and 0 deletions

View File

@ -5,7 +5,9 @@ import (
"fmt" "fmt"
"log" "log"
"logger/data" "logger/data"
"net"
"net/http" "net/http"
"net/rpc"
"time" "time"
"go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson"
@ -49,6 +51,14 @@ func main() {
Models: data.New(client), Models: data.New(client),
} }
// Register the RPC server
err = rpc.Register(new(RPCServer))
if err != nil {
panic(err)
}
go app.rpcListen()
// start web server // start web server
log.Println("Starting service on port", webPort) log.Println("Starting service on port", webPort)
app.serve() app.serve()
@ -88,3 +98,20 @@ func connectToMongo() (*mongo.Client, error) {
return client, nil return client, nil
} }
func (app *Config) rpcListen() error {
log.Println("Starting RPC server on port ", rpcPort)
listen, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%s", rpcPort))
if err != nil {
return err
}
defer listen.Close()
for {
rpcConn, err := listen.Accept()
if err != nil {
continue
}
go rpc.ServeConn(rpcConn)
}
}

View File

@ -0,0 +1,32 @@
package main
import (
"context"
"log"
"logger/data"
"time"
)
type RPCServer struct{}
type RPCPayload struct {
Name string
Data string
}
func (r *RPCServer) LogInfo(payload RPCPayload, resp *string) error {
collection := client.Database("logs").Collection("logs")
_, err := collection.InsertOne(context.TODO(), data.LogEntry{
Name: payload.Name,
Data: payload.Data,
CreatedAt: time.Now(),
})
if err != nil {
log.Println("error writing to mongo", err)
return err
}
*resp = "Processed payload via RPC:" + payload.Name
return nil
}