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):
| Option | Behavior |
|---|---|
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)callsreq.Clone(req.Context())before injectingX-App-Key, so the caller's*http.Requestheaders are never mutated.*DefaultHttpClientalso exposesGetWithContext(ctx, url)andPostWithContext(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 emptytarget). - Prepends
grpc.WithTransportCredentials(insecure.NewCredentials())as the default so any caller-suppliedgrpc.WithTransportCredentials(tlsCreds)overrides it cleanly. - Auth propagation options:
client.WithAppKey(appKey string)— chainsAppKeyUnaryInterceptor(addsx-app-keyto outgoing metadata).client.WithStreamAppKey(appKey string)— chainsAppKeyStreamInterceptor(addsx-app-keyto 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())