Skip to content

Commit

Permalink
add scripts for govet and goimports and autogenerating DOC.md
Browse files Browse the repository at this point in the history
  • Loading branch information
Michal Witkowski committed Feb 26, 2017
1 parent df447e6 commit 6b58677
Show file tree
Hide file tree
Showing 28 changed files with 769 additions and 582 deletions.
File renamed without changes.
2 changes: 1 addition & 1 deletion README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ These are generic building blocks that make it easy to build multiple microservi
The purpose of this repository is to act as a go-to point for such reusable functionality. It contains
some of them itself, but also will link to useful external repos.

`grpc_middleware` itself provides support for chaining interceptors. Se [Documentation](doc.md), but here's a simple example:
`grpc_middleware` itself provides support for chaining interceptors. Se [Documentation](DOC.md), but here's a simple example:

```go
import "github.com/mwitkow/go-grpc-middleware"
Expand Down
86 changes: 86 additions & 0 deletions auth/DOC.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# grpc_auth
--
import "github.com/mwitkow/go-grpc-middleware/auth"

`grpc_auth` a generic server-side auth middleware for gRPC.


### Server Side Auth Middleware

It allows for easy assertion of `:authorization` headers in gRPC calls, be it
HTTP Basic auth, or OAuth2 Bearer tokens.

The middleware takes a user-customizable `AuthFunc`, which can be customized to
verify and extract auth information from the request. The extracted information
can be put in the `context.Context` of handlers downstream for retrieval.

It also allows for per-service implementation overrides of `AuthFunc`. See
`ServiceAuthFuncOverride`.

Please see examples for simple examples of use.

## Usage

#### func AuthFromMD

```go
func AuthFromMD(ctx context.Context, expectedScheme string) (string, error)
```
AuthFromMD is a helper function for extracting the :authorization header from
the gRPC metadata of the request.

It expects the `:authorization` header to be of a certain scheme (e.g. `basic`,
`bearer`), in a case-insensitive format (see rfc2617, sec 1.2). If no such
authorization is found, or the token is of wrong scheme, an error with gRPC
status `Unauthenticated` is returned.

#### func StreamServerInterceptor

```go
func StreamServerInterceptor(authFunc AuthFunc) grpc.StreamServerInterceptor
```
StreamServerInterceptor returns a new unary server interceptors that performs
per-request auth.

#### func UnaryServerInterceptor

```go
func UnaryServerInterceptor(authFunc AuthFunc) grpc.UnaryServerInterceptor
```
UnaryServerInterceptor returns a new unary server interceptors that performs
per-request auth.

#### type AuthFunc

```go
type AuthFunc func(ctx context.Context) (context.Context, error)
```

AuthFunc is the pluggable function that performs authentication.

The passed in `Context` will contain the gRPC metadata.MD object (for
header-based authentication) and the peer.Peer information that can contain
transport-based credentials (e.g. `credentials.AuthInfo`).

The returned context will be propagated to handlers, allowing user changes to
`Context`. However, please make sure that the `Context` returned is a child
`Context` of the one passed in.

If error is returned, its `grpc.Code()` will be returned to the user as well as
the verbatim message. Please make sure you use `codes.Unauthenticated` (lacking
auth) and `codes.PermissionDenied` (authed, but lacking perms) appropriately.

#### type ServiceAuthFuncOverride

```go
type ServiceAuthFuncOverride interface {
AuthFuncOverride(ctx context.Context, fullMethodName string) (context.Context, error)
}
```

ServiceAuthFuncOverride allows a given gRPC service implementation to override
the global `AuthFunc`.

If a service implements the AuthFuncOverride method, it takes precedence over
the `AuthFunc` method, and will be called instead of AuthFunc for all method
invocations within that service.
86 changes: 0 additions & 86 deletions auth/README.md

This file was deleted.

1 change: 1 addition & 0 deletions auth/README.md
13 changes: 7 additions & 6 deletions auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,18 @@ import (

"fmt"

"time"

"github.com/mwitkow/go-grpc-middleware/auth"
"github.com/mwitkow/go-grpc-middleware/testing"
pb_testproto "github.com/mwitkow/go-grpc-middleware/testing/testproto"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"golang.org/x/oauth2"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/oauth"
"google.golang.org/grpc/metadata"
)

var (
Expand Down Expand Up @@ -195,10 +196,10 @@ type fakeOAuth2TokenSource struct {
}

func (ts *fakeOAuth2TokenSource) Token() (*oauth2.Token, error) {
t := &oauth2.Token {
t := &oauth2.Token{
AccessToken: ts.accessToken,
Expiry: time.Now().Add(1 * time.Minute),
TokenType: "bearer",
Expiry: time.Now().Add(1 * time.Minute),
TokenType: "bearer",
}
return t, nil
}
21 changes: 21 additions & 0 deletions checkup.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/bin/bash
# Script that checks up code (govet).

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"

function print_real_go_files {
grep --files-without-match 'DO NOT EDIT!' $(find . -iname '*.go')
}

function govet_all {
ret=0
for i in $(print_real_go_files); do
output=$(go tool vet -all=true -tests=false ${i})
ret=$(($ret | $?))
echo -n ${output}
done;
return ${ret}
}

govet_all
echo "returning $?"
31 changes: 31 additions & 0 deletions fixup.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/bin/bash
# Script that checks the code for errors.

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"

function print_real_go_files {
grep --files-without-match 'DO NOT EDIT!' $(find . -iname '*.go')
}

function generate_markdown {
echo "Generating markdown"
oldpwd=$(pwd)
for i in $(find . -iname 'doc.go'); do
dir=${i%/*}
echo "$dir"
cd ${dir}
${GOPATH}/bin/godocdown -heading=Title -o DOC.md
ln -s DOC.md README.md 2> /dev/null # can fail
cd ${oldpwd}
done;
}

function goimports_all {
echo "Running goimports"
goimports -l -w $(print_real_go_files)
return $?
}

generate_markdown
goimports_all
echo "returning $?"
Empty file removed generate.sh
Empty file.
89 changes: 89 additions & 0 deletions logging/DOC.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# grpc_logging
--
import "github.com/mwitkow/go-grpc-middleware/logging"

gRPC middleware logging.

`grpc_logging` is a "mother" package for other specific gRPC logging middleware.

General functionality across all logging middleware:

* Extract(ctx) function that provides a request-scoped logger with pre-defined fields
* log statement on completion of handling with customizeable log levels, gRPC status code and error message logging
* automatic request field to log field extraction, either through code-generated data or field annotations

### Concrete logging middleware for use in user-code handlers is available in
### subpackages

* zap
* logrus

### The functions and methods in this package should only be consumed by gRPC
### logging middleware and other middlewares that want to add metadata to the
logging context of the request.

## Usage

```go
var (
// InternalContextMarker is the Context value marker used by *all* logging middleware.
// The logging middleware object must interf
InternalContextMarker = &grpcLoggerMarker{}
)
```

#### func CodeGenRequestLogFieldExtractor

```go
func CodeGenRequestLogFieldExtractor(fullMethod string, req interface{}) (keys []string, values []interface{})
```
CodeGenRequestLogFieldExtractor is a function that relies on code-generated
functions that export log fields from requests. These are usually coming from a
protoc-plugin that generates additional information based on custom field
options.

#### func TagedRequestFiledExtractor

```go
func TagedRequestFiledExtractor(fullMethod string, req interface{}) (keys []string, values []interface{})
```
TagedRequestFiledExtractor is a function that relies on Go struct tags to export
log fields from requests. These are usualy coming from a protoc-plugin, such as
Gogo protobuf.

message Metadata {
repeated string tags = 1 [ (gogoproto.moretags) = "log_field:\"meta_tags\"" ];
}

It requires the tag to be `log_field` and is recursively executed through all
non-repeated structs.

#### type Metadata

```go
type Metadata interface {
AddFieldsFromMiddleware(keys []string, values []interface{})
}
```

Metadata is a common interface for interacting with the request-scope of a
logger provided by any middleware.

#### func ExtractMetadata

```go
func ExtractMetadata(ctx context.Context) Metadata
```
ExtractMetadata allows other middleware to access the metadata (e.g.
request-scope fields) of any logging middleware.

#### type RequestLogFieldExtractorFunc

```go
type RequestLogFieldExtractorFunc func(fullMethod string, req interface{}) (keys []string, values []interface{})
```

RequestLogFieldExtractorFunc is a user-provided function that extracts field
information from a gRPC request. It is called from every logging middleware on
arrival of unary request or a server-stream request. Keys and values will be
added to the logging request context.
Loading

0 comments on commit 6b58677

Please sign in to comment.