Implement config singleton (#1268)

* Implement config singleton

* Pass token in grpc request headers

* Refactor BearerScheme

* Fix typo
This commit is contained in:
ben-toogood 2020-02-28 12:58:27 +00:00 committed by Vasiliy Tolstov
parent cb22a88ba3
commit 42e9cc97e8

View File

@ -18,6 +18,7 @@ import (
"github.com/micro/go-micro/v2/errors" "github.com/micro/go-micro/v2/errors"
"github.com/micro/go-micro/v2/metadata" "github.com/micro/go-micro/v2/metadata"
"github.com/micro/go-micro/v2/registry" "github.com/micro/go-micro/v2/registry"
"github.com/micro/go-micro/v2/util/config"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials"
@ -25,6 +26,10 @@ import (
gmetadata "google.golang.org/grpc/metadata" gmetadata "google.golang.org/grpc/metadata"
) )
var (
BearerScheme = "Bearer "
)
type grpcClient struct { type grpcClient struct {
opts client.Options opts client.Options
pool *pool pool *pool
@ -128,6 +133,10 @@ func (g *grpcClient) call(ctx context.Context, node *registry.Node, req client.R
header["timeout"] = fmt.Sprintf("%d", opts.RequestTimeout) header["timeout"] = fmt.Sprintf("%d", opts.RequestTimeout)
// set the content type for the request // set the content type for the request
header["x-content-type"] = req.ContentType() header["x-content-type"] = req.ContentType()
// set the authorization token if one is saved locally
if token, err := config.Get("token"); err == nil && len(token) > 0 {
header["authorization"] = BearerScheme + token
}
md := gmetadata.New(header) md := gmetadata.New(header)
ctx = gmetadata.NewOutgoingContext(ctx, md) ctx = gmetadata.NewOutgoingContext(ctx, md)