Skip to content

Commit

Permalink
Merge pull request #10 from ysugimoto/append-custom-context-on-middle…
Browse files Browse the repository at this point in the history
…ware

Change middleware interface
  • Loading branch information
ysugimoto authored Jun 23, 2020
2 parents 6232f2a + 0de7d0b commit 4661a67
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@

![image](https://raw.githubusercontent.com/ysugimoto/grpc-graphql-gateway/master/misc/grpc-graphql-gateway.png)

## Change Log

### v0.9.1

#### Changed middleware fucntion type

On MiddlewareFunc, you need to return `context.Context` as first return value. this is because we need to make custom metadata to gRPC on middleware process.
If you are already using your onw middleware, plase change its interface. see https://github.com/ysugimoto/grpc-graphql-gateway/pull/10

## Motivation

On API development, frequently we choose some IDL, in order to manage API definitions from a file.
Expand Down
4 changes: 2 additions & 2 deletions runtime/middlewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ import (

// Cors is middelware function to provide CORS headers to response headers
func Cors() MiddlewareFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) (context.Context, error) {
w.Header().Set("Access-Control-Allow-Origin", r.URL.Host)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Max-Age", "1728000")
return nil
return ctx, nil
}
}
7 changes: 4 additions & 3 deletions runtime/mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (

type (
// MiddlewareFunc type definition
MiddlewareFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request) error
MiddlewareFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request) (context.Context, error)

// Custom error handler which is called on graphql result has an error
GraphqlErrorHandler func(errs gqlerrors.FormattedErrors)
Expand Down Expand Up @@ -92,9 +92,10 @@ func (s *ServeMux) Use(ms ...MiddlewareFunc) *ServeMux {
// ServeHTTP implements http.Handler
func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()

for _, m := range s.middlewares {
if err := m(ctx, w, r); err != nil {
var err error
ctx, err = m(ctx, w, r)
if err != nil {
http.Error(w, "middleware error occurred: "+err.Error(), http.StatusInternalServerError)
return
}
Expand Down

0 comments on commit 4661a67

Please sign in to comment.