Add rpc listener to logger service
This commit is contained in:
parent
41dab037ce
commit
990385b3e7
@ -5,7 +5,9 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"logger/data"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/rpc"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
@ -49,6 +51,14 @@ func main() {
|
||||
Models: data.New(client),
|
||||
}
|
||||
|
||||
// Register the RPC server
|
||||
err = rpc.Register(new(RPCServer))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
go app.rpcListen()
|
||||
|
||||
// start web server
|
||||
log.Println("Starting service on port", webPort)
|
||||
app.serve()
|
||||
@ -88,3 +98,20 @@ func connectToMongo() (*mongo.Client, error) {
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
32
logger-service/cmd/api/rpc.go
Normal file
32
logger-service/cmd/api/rpc.go
Normal 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
|
||||
}
|
Loading…
Reference in New Issue
Block a user