github.com/dgraph-io/dgraph@v1.2.8/graphql/api/context.go (about) 1 /* 2 * Copyright 2019 Dgraph Labs, Inc. and Contributors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package api 18 19 import ( 20 "context" 21 "net/http" 22 23 "github.com/google/uuid" 24 ) 25 26 // Various functions for getting and setting context, etc. used 27 // throughout the GraphQL API. 28 29 type apiKey string 30 31 const ( 32 requestID = apiKey("requestID") 33 nilRequestID = "a1111111-b222-c333-d444-e55555555555" 34 35 gqlQuery = apiKey("gqlQuery") 36 nilGQLQuery = "aGraphQLQuery {}" 37 ) 38 39 // WithRequestID adds a HTTP middleware handler that sets a UUID as request ID 40 // into the handler chain. 41 func WithRequestID(h http.Handler) http.Handler { 42 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 43 reqID := uuid.New().String() 44 h.ServeHTTP(w, r.WithContext( 45 context.WithValue(r.Context(), requestID, reqID))) 46 }) 47 } 48 49 // WithQueryString returns a new context where QueryString() returns query. 50 func WithQueryString(ctx context.Context, query string) context.Context { 51 return context.WithValue(ctx, gqlQuery, query) 52 } 53 54 // RequestID gets the request ID from a context. If no request ID is set, 55 // it returns "a1111111-b222-c333-d444-e55555555555". 56 func RequestID(ctx context.Context) string { 57 return stringFromContext(ctx, requestID, nilRequestID) 58 } 59 60 // QueryString gets the GraphQL query from a context. If no query is set, 61 // it returns "aGraphQLQuery {}" 62 func QueryString(ctx context.Context) string { 63 return stringFromContext(ctx, gqlQuery, nilGQLQuery) 64 } 65 66 func stringFromContext(ctx context.Context, key apiKey, def string) string { 67 if val := ctx.Value(key); val != nil { 68 if str, ok := val.(string); ok { 69 return str 70 } 71 } 72 return def 73 }