gomicro

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 13, 2026 License: Apache-2.0 Imports: 23 Imported by: 2

README

gomicro

gomicro provides small building blocks for Go microservices that expose gRPC APIs, optional HTTP gateways, structured logging, JWT-based authentication helpers, and connection utilities.

The repository is intentionally lightweight: you assemble the pieces you need instead of adopting a large framework.

Packages

  • github.com/gidyon/gomicro: service bootstrap, gRPC/HTTP startup, and logging helpers.
  • github.com/gidyon/gomicro/pkg/conn: SQL and gRPC client connection helpers.
  • github.com/gidyon/gomicro/pkg/grpc: reusable gRPC server middleware for auth, logging, payload logging, and panic recovery.
  • github.com/gidyon/gomicro/pkg/grpc/auth: JWT authentication and authorization helpers for gRPC services.

Quick Start

Create a service and register plain HTTP endpoints:

svc, err := gomicro.NewService(&gomicro.Options{
    ServiceName: "users",
    HttpPort:    8080,
    GrpcPort:    9090,
})
if err != nil {
    return err
}

svc.AddEndpointFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    _, _ = w.Write([]byte("ok"))
})

Add gRPC middleware before initialization:

loggerInterceptors, streamLoggerInterceptors := middleware.AddLogging(zap.NewNop())
svc.AddGRPCUnaryServerInterceptors(loggerInterceptors...)
svc.AddGRPCStreamServerInterceptors(streamLoggerInterceptors...)

recoveryUnary, recoveryStream := middleware.AddRecovery()
svc.AddGRPCUnaryServerInterceptors(recoveryUnary...)
svc.AddGRPCStreamServerInterceptors(recoveryStream...)

Initialize JWT auth for a gRPC service:

authAPI := grpcauth.NewAPI([]byte("secret"), "users", "users-api")

token, err := authAPI.GenToken(context.Background(), &grpcauth.Payload{
    ID:        "user-123",
    ProjectID: "project-1",
    Group:     grpcauth.DefaultUserGroup(),
}, time.Now().Add(time.Hour))
if err != nil {
    return err
}

md, _ := authAPI.GetMetadataFromJwt(token)
_ = md

Dial a gRPC service:

conn, err := conn.DialGrpcService(context.Background(), &conn.GrpcDialOptions{
    Address: "localhost:9090",
    DialOptions: []grpc.DialOption{
        grpc.WithTransportCredentials(insecure.NewCredentials()),
    },
})
if err != nil {
    return err
}
defer conn.Close()

Open a MySQL connection with pool settings:

db, err := conn.OpenSql(&conn.DbOptions{
    Name:    "users",
    Address: "127.0.0.1:3306",
    User:    "root",
    Schema:  "users",
    ConnPool: &conn.DbPoolSettings{
        MaxIdleConns: 5,
        MaxOpenConns: 20,
    },
})
if err != nil {
    return err
}
defer db.Close()

Lifecycle Notes

  • Add server/client interceptors and runtime mux options before calling Initialize or Start.
  • NewService applies safe defaults when options are omitted.
  • When TLS is enabled, provide both TlSCertFile and TlSKeyFile.
  • Start blocks until the service stops; use Initialize if you need to prepare the service before starting it elsewhere.

Testing

Run the full suite with:

GOCACHE=/tmp/go-build go test ./...

Documentation

Overview

Package gomicro provides lightweight helpers for building gRPC-first microservices with optional HTTP endpoints and grpc-gateway integration.

The package centers around Service, which collects server options, interceptors, gateway options, HTTP middleware, and listeners before the process is started. Safe defaults are applied for common settings such as service name, ports, logger, and runtime mux path.

Typical usage:

  1. Create a service with NewService.
  2. Add HTTP routes, gRPC interceptors, and dial/server options.
  3. Register services on GRPCServer() and handlers on RuntimeMux().
  4. Call Initialize or Start.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewLogger

func NewLogger(serviceName string, level zerolog.Level) grpclog.LoggerV2

NewLogger creates a grpclog.LoggerV2 backed by zerolog. If serviceName is blank, "app" is used.

Types

type Options

type Options struct {
	// ServiceName identifies the service in logs and defaults.
	ServiceName string
	// HttpPort is the listener port for HTTP traffic and for combined HTTP/gRPC
	// traffic when TLS is enabled.
	HttpPort int
	// GrpcPort is the dedicated listener port for insecure gRPC traffic.
	GrpcPort int
	// Logger is used for service lifecycle logging. If nil, a default logger is created.
	Logger grpclog.LoggerV2
	// RuntimeMuxEndpoint is the path prefix used when mounting the grpc-gateway mux.
	RuntimeMuxEndpoint      string
	ServerReadTimeout       time.Duration
	ServerWriteTimeout      time.Duration
	ServerReadHeaderTimeout time.Duration
	// NowFunc overrides the clock used internally by the service.
	NowFunc func() time.Time
	// TLSEnabled enables secure serving on the HTTP port.
	TLSEnabled bool
	// TlSCertFile is the server certificate path used when TLS is enabled.
	TlSCertFile string
	// TlSKeyFile is the private key path used when TLS is enabled.
	TlSKeyFile string
	// TLSServerName is used by the local gateway client when dialing the secure gRPC endpoint.
	TLSServerName string
}

Options configures a Service.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service collects the state needed to bootstrap and run a gRPC service with optional HTTP endpoints and grpc-gateway support.

func NewService

func NewService(opt *Options) (*Service, error)

NewService creates a Service with safe defaults for omitted options.

Example
svc, err := NewService(&Options{
	ServiceName: "users",
	HttpPort:    8080,
	GrpcPort:    9090,
	Logger:      NewLogger("users", zerolog.InfoLevel),
})
if err != nil {
	panic(err)
}

svc.AddEndpointFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
})

func (*Service) AddEndpoint

func (service *Service) AddEndpoint(pattern string, handler http.Handler)

AddEndpoint registers the handler for the given pattern. If a handler already exists for pattern, Handle panics.

func (*Service) AddEndpointFunc

func (service *Service) AddEndpointFunc(pattern string, handleFunc http.HandlerFunc)

AddEndpointFunc registers the handler function for the given pattern.

func (*Service) AddGRPCDialOptions

func (service *Service) AddGRPCDialOptions(dialOptions ...grpc.DialOption)

AddGRPCDialOptions appends dial options used by the service's internal gRPC client.

func (*Service) AddGRPCServerOptions

func (service *Service) AddGRPCServerOptions(serverOptions ...grpc.ServerOption)

AddGRPCServerOptions appends server options used when constructing the gRPC server.

func (*Service) AddGRPCStreamClientInterceptors

func (service *Service) AddGRPCStreamClientInterceptors(
	streamInterceptors ...grpc.StreamClientInterceptor,
)

AddGRPCStreamClientInterceptors appends stream client interceptors used by the internal gateway client.

func (*Service) AddGRPCStreamServerInterceptors

func (service *Service) AddGRPCStreamServerInterceptors(
	streamInterceptors ...grpc.StreamServerInterceptor,
)

AddGRPCStreamServerInterceptors appends stream server interceptors.

func (*Service) AddGRPCUnaryClientInterceptors

func (service *Service) AddGRPCUnaryClientInterceptors(
	unaryInterceptors ...grpc.UnaryClientInterceptor,
)

AddGRPCUnaryClientInterceptors appends unary client interceptors used by the internal gateway client.

func (*Service) AddGRPCUnaryServerInterceptors

func (service *Service) AddGRPCUnaryServerInterceptors(
	unaryInterceptors ...grpc.UnaryServerInterceptor,
)

AddGRPCUnaryServerInterceptors appends unary server interceptors.

func (*Service) AddHTTPMiddlewares

func (service *Service) AddHTTPMiddlewares(middlewares ...func(http.Handler) http.Handler)

AddHTTPMiddlewares appends HTTP middleware in the order they should wrap handlers.

Example
svc, err := NewService(nil)
if err != nil {
	panic(err)
}

svc.AddHTTPMiddlewares(func(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-Service", "gomicro")
		next.ServeHTTP(w, r)
	})
})

func (*Service) AddRuntimeMuxOptions

func (service *Service) AddRuntimeMuxOptions(serveMuxOptions ...runtime.ServeMuxOption)

AddRuntimeMuxOptions appends grpc-gateway ServeMux options applied during initialization.

func (*Service) ClientConn

func (service *Service) ClientConn() *grpc.ClientConn

ClientConn returns the internal gRPC client connection used by the gateway.

func (*Service) GRPCServer

func (service *Service) GRPCServer() *grpc.Server

GRPCServer returns the gRPC server instance for service registration.

func (*Service) Initialize

func (service *Service) Initialize(ctx context.Context)

Initialize initializes service without starting it.

func (*Service) RuntimeMux

func (service *Service) RuntimeMux() *runtime.ServeMux

RuntimeMux returns the grpc-gateway mux used by the reverse proxy handler. Register generated gateway handlers on the returned mux.

func (*Service) Start

func (service *Service) Start(ctx context.Context, initFn func() error)

Start starts grpc and http server to serve requests.

Directories

Path Synopsis
pkg
conn
Package conn contains connection helpers for the most common outbound dependencies used by gomicro services.
Package conn contains connection helpers for the most common outbound dependencies used by gomicro services.
grpc
Package middleware provides reusable gRPC server interceptors for common production concerns such as authentication, structured logging, payload logging, and panic recovery.
Package middleware provides reusable gRPC server interceptors for common production concerns such as authentication, structured logging, payload logging, and panic recovery.
grpc/auth
`grpcauth` is an authentication and authorization gRPC server side authentication wrappers.
`grpcauth` is an authentication and authorization gRPC server side authentication wrappers.
grpc/zaplogger
Package zaplogger adapts zap loggers for gRPC internals and provides a small initialization helper for structured JSON logging.
Package zaplogger adapts zap loggers for gRPC internals and provides a small initialization helper for structured JSON logging.
utils

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL