Skip to content

Instantly share code, notes, and snippets.

@Ell
Created May 31, 2016 15:56
Show Gist options
  • Save Ell/2048c688d405661fd0bbe0d81d6bf6f6 to your computer and use it in GitHub Desktop.
Save Ell/2048c688d405661fd0bbe0d81d6bf6f6 to your computer and use it in GitHub Desktop.
package server
import (
"errors"
"github.com/ell/tunes/mopidy"
"golang.org/x/net/context"
"log"
"net/http"
)
func withMopidyClient(client *mopidy.Client, h ContextHandler) ContextHandler {
return ContextHandlerFunc(func(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
ctx = context.WithValue(ctx, mopidyClientKey, client)
return h.ServeHTTPContext(ctx, w, req)
})
}
func withAPIKeyAuthentication(apiKey string, h ContextHandler) ContextHandler {
return ContextHandlerFunc(func(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
apiHeader := req.Header.Get("Authorization")
log.Printf("Got auth header value: %s", apiHeader)
if apiHeader != apiKey {
return errors.New("Invalid API key provided.")
}
return h.ServeHTTPContext(ctx, w, req)
})
}
func withDatabase(db *Database, h ContextHandler) ContextHandler {
return ContextHandlerFunc(func(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
ctx = context.WithValue(ctx, databaseKey, db)
return h.ServeHTTPContext(ctx, w, req)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment