80 lines
1.8 KiB
Go
80 lines
1.8 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
|
|
"github.com/jmoiron/sqlx"
|
|
"go.mongodb.org/mongo-driver/v2/mongo"
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/protobuf/proto"
|
|
)
|
|
|
|
func New(options ...Option) *App {
|
|
a := &App{
|
|
ctx: context.Background(),
|
|
router: chi.NewRouter(),
|
|
grpcServer: grpc.NewServer(),
|
|
httpServer: new(http.Server),
|
|
}
|
|
for _, option := range options {
|
|
option(a)
|
|
}
|
|
return a
|
|
}
|
|
|
|
type App struct {
|
|
ctx context.Context
|
|
router *chi.Mux
|
|
grpcServer *grpc.Server
|
|
httpServer *http.Server
|
|
mux *runtime.ServeMux
|
|
postgres *sqlx.DB
|
|
mongo *mongo.Client
|
|
closers []closeFunc
|
|
serviceRegistry []registerServiceFunc
|
|
gatewayRegistry []registerGatewayFunc
|
|
config struct {
|
|
grpcAddr string
|
|
httpAddr string
|
|
postgresURI string
|
|
mongoURI string
|
|
withGrpc bool
|
|
withSwagger bool
|
|
withStatic bool
|
|
forwardResponse forwardResponseFunc
|
|
}
|
|
}
|
|
|
|
const (
|
|
defaultHttpAddr = ":8000"
|
|
defaultGrpcAddr = ":9000"
|
|
)
|
|
|
|
type forwardResponseFunc func(context.Context, http.ResponseWriter, proto.Message) error
|
|
type closeFunc func() error
|
|
type registerServiceFunc func(gs *grpc.Server)
|
|
type registerGatewayFunc func(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error
|
|
|
|
func (a *App) RegisterServices(fn registerServiceFunc) {
|
|
a.serviceRegistry = append(a.serviceRegistry, fn)
|
|
}
|
|
|
|
func (a *App) RegisterGateways(fns ...registerGatewayFunc) {
|
|
a.gatewayRegistry = append(a.gatewayRegistry, fns...)
|
|
}
|
|
|
|
func (a *App) GRPC() *grpc.Server {
|
|
return a.grpcServer
|
|
}
|
|
|
|
func (a *App) HTTP() *http.Server {
|
|
return a.httpServer
|
|
}
|
|
|
|
func (a *App) Router() *chi.Mux {
|
|
return a.router
|
|
}
|