cake_crm/cmd/cake_crm/main.go

114 lines
2.9 KiB
Go

package main
import (
"cake_crm/internal/app"
"cake_crm/internal/modules/messenger/telegram"
"cake_crm/internal/modules/storage/storage_file"
"cake_crm/internal/services/cart"
"cake_crm/internal/services/order"
proto "cake_crm/proto"
"context"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"log"
"net"
"net/http"
"os"
"strconv"
"strings"
)
func main() {
storage := storage_file.NewStorageFile()
cartService := cart.NewService(storage)
orderService := order.NewService()
tokenData, err := os.ReadFile("resources/order_bot_token.txt")
if err != nil {
panic(err)
}
token := strings.TrimSpace(string(tokenData))
chatIdData, err := os.ReadFile("resources/telegram_order_chat_id.txt")
if err != nil {
panic(err)
}
chatID, err := strconv.ParseInt(strings.TrimSpace(string(chatIdData)), 10, 64)
if err != nil {
panic(err)
}
messenger, err := telegram.NewMessenger(chatID, token)
if err != nil {
panic(err)
}
// Create a listener on TCP port
lis, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatalln("Failed to listen:", err)
}
// Create a gRPC server object
s := grpc.NewServer()
// Attach the Greeter service to the server
proto.RegisterCRMServer(s, app.NewServer(storage, messenger, cartService, orderService))
// Serve gRPC server
log.Println("Serving gRPC on 0.0.0.0:8080")
go func() {
log.Fatalln(s.Serve(lis))
}()
// Create a client connection to the gRPC server we just started
// This is where the gRPC-Gateway proxies the requests
conn, err := grpc.NewClient(
"0.0.0.0:8080",
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
log.Fatalln("Failed to dial server:", err)
}
mux := runtime.NewServeMux()
// Register Greeter
err = proto.RegisterCRMHandler(context.Background(), mux, conn)
if err != nil {
log.Fatalln("Failed to register gateway:", err)
}
err = mux.HandlePath("GET", "/swagger", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
data, err := os.ReadFile("resources/main.swagger.json")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
_, _ = w.Write(data)
})
if err != nil {
panic(err)
}
log.Println("Serving swagger json on http://0.0.0.0:8090/swagger")
gwServer := &http.Server{
Addr: ":8090",
Handler: cors(mux),
}
log.Println("Serving gRPC-Gateway on http://0.0.0.0:8090")
log.Fatalln(gwServer.ListenAndServe())
}
func cors(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization, ResponseType")
if r.Method == "OPTIONS" {
return
}
h.ServeHTTP(w, r)
})
}