grpc

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 12 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-grpc

A lightweight gRPC server factory for Go. Handles HTTP/2, TLS, panic recovery, structured logging, and graceful shutdown out of the box — so your service setup stays minimal.

Requirements

Installation

go get codeberg.org/obadness/go-grpc

Quick start

import (
    gogrpc "codeberg.org/obadness/go-grpc"
)

srv := gogrpc.NewServer(gogrpc.Config{
    Host: "0.0.0.0",
    Port: 50051,
    Registrars: []gogrpc.Registrar{
        &UserServiceHandler{},
        &OrderServiceHandler{},
    },
    Reflection: true,
})

if err := srv.Serve(ctx); err != nil {
    log.Fatal(err)
}

Config

Field Type Description
Host string Bind address e.g. "0.0.0.0" or "localhost"
Port int Port to listen on
Credentials credentials.TransportCredentials TLS credentials — plain TCP if nil
UnaryInterceptors []grpc.UnaryServerInterceptor Additional unary interceptors — run innermost after built-ins
StreamInterceptors []grpc.StreamServerInterceptor Additional stream interceptors — run innermost after built-ins
Registrars []Registrar Services to register on the server
MaxMessageSize int Max send/receive message size in bytes — defaults to 4MB
ShutdownTimeout time.Duration Graceful shutdown timeout — defaults to 10s
Reflection bool Enable gRPC server reflection — useful for tools like grpcurl

Registrar interface

Implement Registrar on your service handler to register it with the server:

type Registrar interface {
    Register(server *grpc.Server)
}
// example handler
type UserServiceHandler struct{}

func (h *UserServiceHandler) Register(server *grpc.Server) {
    userv1.RegisterUserServiceServer(server, h)
}

Built-in interceptors

Two interceptors are applied automatically to every handler, for both unary and streaming RPCs:

Request → Recovery → Logging → Handler → Logging → Recovery → Response

Recovery is outermost so it catches panics from all inner interceptors and the handler. Logging sits inside Recovery so it always records duration and status code.

Recovery

Catches panics in unary and streaming handlers. On panic it:

  • Logs the method name, panic value, and full stack trace via slog
  • Returns a codes.Internal status error to the client
// automatically applied — no configuration needed
RecoveryInterceptor()
StreamRecoveryInterceptor()
Logging

Logs every RPC call via slog. On success logs method and duration. On error also logs the gRPC status code.

// automatically applied — no configuration needed
LoggingInterceptor()
StreamLoggingInterceptor()

Example log output:

INFO grpc call completed method=/user.v1.UserService/GetUser duration=1.2ms
INFO grpc call failed method=/user.v1.UserService/CreateUser duration=3.4ms code=already_exists error="..."
INFO grpc stream completed method=/user.v1.UserService/WatchUsers client_stream=false server_stream=true duration=30.1s
INFO grpc stream failed method=/user.v1.UserService/WatchUsers client_stream=false server_stream=true duration=2.1s code=cancelled error="..."
Custom interceptors

Additional interceptors are appended after the built-ins and run closest to the handler:

srv := gogrpc.NewServer(gogrpc.Config{
    UnaryInterceptors: []grpc.UnaryServerInterceptor{
        authInterceptor,
        rateLimitInterceptor,
    },
    StreamInterceptors: []grpc.StreamServerInterceptor{
        authStreamInterceptor,
    },
})

TLS

Pass transport credentials to enable TLS:

creds, err := credentials.NewServerTLSFromFile("cert.pem", "key.pem")
if err != nil {
    log.Fatal(err)
}

srv := gogrpc.NewServer(gogrpc.Config{
    Credentials: creds,
})

Omit Credentials for plain TCP (useful behind a TLS-terminating proxy).


Reflection

Enable server reflection for use with tools like grpcurl and Postman:

gogrpc.NewServer(gogrpc.Config{
    Reflection: true,
})
grpcurl -plaintext localhost:50051 list

Graceful shutdown

Serve accepts a context.Context. When the context is cancelled the server calls GracefulStop, waiting for in-flight RPCs to complete. If they do not finish within the shutdown timeout, Stop is called to force close:

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()

if err := srv.Serve(ctx); err != nil {
    log.Fatal(err)
}
gogrpc.NewServer(gogrpc.Config{
    ShutdownTimeout: 30 * time.Second, // default: 10s
})

Keepalive

The server is configured with keepalive parameters by default:

Parameter Value
Time 30s — ping the client after 30s of inactivity
Timeout 10s — close the connection if no response within 10s

Project structure

go-grpc/
├── main.go      # NewServer(), Server, Config, Registrar
├── unary.go     # LoggingInterceptor(), RecoveryInterceptor()
└── stream.go    # StreamLoggingInterceptor(), StreamRecoveryInterceptor()

License

Copyright (C) 2026 Jeremy Obado. All rights reserved.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func LoggingInterceptor

func LoggingInterceptor() grpc.UnaryServerInterceptor

func RecoveryInterceptor

func RecoveryInterceptor() grpc.UnaryServerInterceptor

func StreamLoggingInterceptor

func StreamLoggingInterceptor() grpc.StreamServerInterceptor

func StreamRecoveryInterceptor

func StreamRecoveryInterceptor() grpc.StreamServerInterceptor

Types

type Config

type Config struct {
	Host               string
	Port               int
	Credentials        credentials.TransportCredentials
	UnaryInterceptors  []grpc.UnaryServerInterceptor
	StreamInterceptors []grpc.StreamServerInterceptor
	Registrars         []Registrar
	MaxMessageSize     int           // defaults to 4MB if zero
	ShutdownTimeout    time.Duration // defaults to 10s if zero
	Reflection         bool
}

type Registrar

type Registrar interface {
	Register(server *grpc.Server)
}

type Server

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

func NewServer

func NewServer(cfg Config) *Server

func (*Server) Serve

func (svr *Server) Serve(ctx context.Context) error

Jump to

Keyboard shortcuts

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