Skip to content

HTTP & gRPC Clients (boot/client) ​

github.com/mmycin/goforge/boot/client provides lightweight, auth-aware HTTP and gRPC clients for service-to-service communication and integration testing.


HTTP Client (boot/client/http_client.go) ​

go
type HttpClient interface {
	Do(req *http.Request) (*http.Response, error)
	Get(url string) (*http.Response, error)
	Post(url string, contentType string, body []byte) (*http.Response, error)
}

NewHttpClient(opts ...HttpOption) HttpClient returns *DefaultHttpClient (default timeout: 10s):

OptionBehavior
client.WithTimeout(d time.Duration)Sets http.Client.Timeout.
client.WithHttpAppKey(apiKey string)Attaches X-App-Key: <apiKey> on every request.

Non-Mutating Do() & Context Methods ​

  • Do(req) calls req.Clone(req.Context()) before injecting X-App-Key, so the caller's *http.Request headers are never mutated.
  • *DefaultHttpClient also exposes GetWithContext(ctx, url) and PostWithContext(ctx, url, contentType, body).
go
hc := client.NewHttpClient(
	client.WithTimeout(5*time.Second),
	client.WithHttpAppKey(os.Getenv("APP_KEY")),
)
resp, err := hc.(*client.DefaultHttpClient).GetWithContext(ctx, "http://127.0.0.1:3000/api/todos")

gRPC Client (boot/client/grpc_client.go) ​

go
type Client interface {
	Conn() *grpc.ClientConn
	Close() error
	Target() string
}

func NewGrpcClient(target string, opts ...grpc.DialOption) (Client, error)

Key Behaviors ​

  • Uses modern grpc.NewClient(target, allOpts...) (rejects empty target).
  • Prepends grpc.WithTransportCredentials(insecure.NewCredentials()) as the default so any caller-supplied grpc.WithTransportCredentials(tlsCreds) overrides it cleanly.
  • Auth propagation options:
    • client.WithAppKey(appKey string) — chains AppKeyUnaryInterceptor (adds x-app-key to outgoing metadata).
    • client.WithStreamAppKey(appKey string) — chains AppKeyStreamInterceptor (adds x-app-key to outgoing stream metadata).
go
gc, err := client.NewGrpcClient(
	"127.0.0.1:50051",
	client.WithAppKey(appKey),
	client.WithStreamAppKey(appKey),
)
if err != nil {
	return err
}
defer gc.Close()

stub := pb.NewTodoServiceClient(gc.Conn())

Released under the Apache-2.0 License.