cmd/routed: fix header getting

This commit is contained in:
Cadey Ratio 2018-01-21 09:07:21 -08:00
parent e7d494513d
commit b9a78fa3bf
4 changed files with 38 additions and 30 deletions

View File

@ -7,6 +7,7 @@ import (
"time"
"git.xeserv.us/xena/route/internal/database"
"git.xeserv.us/xena/route/internal/middleware"
"github.com/Xe/ln"
"github.com/twitchtv/twirp"
"golang.org/x/net/trace"
@ -44,7 +45,7 @@ func (s *Server) makeTwirpHooks() *twirp.ServerHooks {
"twirp_service": svc,
})
hdr, ok := twirp.HTTPRequestHeaders(ctx)
hdr, ok := middleware.GetHeaders(ctx)
if !ok {
return ctx, errors.New("can't get request headers")
}

View File

@ -160,7 +160,7 @@ func New(cfg Config) (*Server, error) {
hs := &http.Server{
TLSConfig: tc,
Addr: cfg.GRPCAddr,
Handler: middleware.Twirp(middleware.Trace("twirp-https")(mux)),
Handler: middleware.SaveHeaders(middleware.Trace("twirp-https")(mux)),
}
go hs.ListenAndServeTLS("", "")

View File

@ -0,0 +1,35 @@
package middleware
import (
"context"
"net/http"
)
type headerKey int
const hdrKey headerKey = iota
// GetHeaders fetches http headers from the request context.
func GetHeaders(ctx context.Context) (http.Header, bool) {
h, ok := ctx.Value(hdrKey).(http.Header)
if !ok {
return http.Header{}, false
}
return h, true
}
// SaveHeaders adds the needed values to the request context for twirp services.
func SaveHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if ctx == nil {
panic("context is nil")
}
ctx = context.WithValue(ctx, hdrKey, r.Header)
next.ServeHTTP(w, r.WithContext(ctx))
})
}

View File

@ -1,28 +0,0 @@
package middleware
import (
"context"
"net/http"
"github.com/Xe/ln"
"github.com/twitchtv/twirp"
)
// Twirp adds the needed values to the request context for twirp services.
func Twirp(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if ctx == nil {
panic("context is nil")
}
ctx, err := twirp.WithHTTPRequestHeaders(ctx, r.Header)
if err != nil {
ln.Error(context.Background(), err, ln.Action("can't get request headers"))
http.Error(w, err.Error(), http.StatusInternalServerError)
}
next.ServeHTTP(w, r.WithContext(ctx))
})
}