udemy-go-microservices/logger-service/cmd/api/main.go

118 lines
2.1 KiB
Go
Raw Normal View History

package main
import (
"context"
2024-08-29 11:24:36 +00:00
"fmt"
"log"
2024-08-29 11:24:36 +00:00
"logger/data"
2024-09-06 18:27:53 +00:00
"net"
2024-08-29 11:24:36 +00:00
"net/http"
2024-09-06 18:27:53 +00:00
"net/rpc"
2024-08-28 21:09:26 +00:00
"time"
2024-08-31 20:56:25 +00:00
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
webPort = "80"
rpcPort = "5001"
mongoURL = "mongodb://mongo:27017"
gRpcPort = "50001"
)
var client *mongo.Client
2024-08-29 11:24:36 +00:00
type Config struct {
Models data.Models
}
func main() {
// connect to mongo
mongoClient, err := connectToMongo()
if err != nil {
log.Panic(err)
}
2024-08-28 21:09:26 +00:00
// create a context in order to disconnect
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// close connection
defer func() {
2024-08-28 21:09:26 +00:00
if err = mongoClient.Disconnect(ctx); err != nil {
panic(err)
}
}()
2024-08-31 20:56:25 +00:00
client = mongoClient
2024-08-29 11:24:36 +00:00
app := Config{
Models: data.New(client),
}
2024-09-06 18:27:53 +00:00
// Register the RPC server
err = rpc.Register(new(RPCServer))
if err != nil {
panic(err)
}
go app.rpcListen()
2024-08-29 11:24:36 +00:00
// start web server
2024-08-29 11:48:47 +00:00
log.Println("Starting service on port", webPort)
app.serve()
2024-08-29 11:24:36 +00:00
}
func (app *Config) serve() {
srv := &http.Server{
Addr: fmt.Sprintf(":%s", webPort),
Handler: app.routes(),
}
err := srv.ListenAndServe()
if err != nil {
log.Panic(err)
}
}
func connectToMongo() (*mongo.Client, error) {
clientOptions := options.Client().ApplyURI(mongoURL)
clientOptions.SetAuth(options.Credential{
Username: "admin",
Password: "password",
})
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Println("Error connecting:", err)
return nil, err
}
2024-08-31 20:56:25 +00:00
var result bson.M
2024-09-01 05:39:42 +00:00
if err = client.Database("admin").RunCommand(context.TODO(), bson.D{{Key: "ping", Value: 1}}).Decode(&result); err != nil {
2024-08-31 20:56:25 +00:00
log.Println("Error ping:", err)
return nil, err
}
2024-08-29 11:48:47 +00:00
log.Println("Connected to Mongo")
return client, nil
}
2024-09-06 18:27:53 +00:00
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)
}
}