vitess.io/vitess@v0.16.2/go/vt/callinfo/callinfo.go (about) 1 /* 2 Copyright 2019 The Vitess Authors. 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 callinfo stores custom values into the Context 18 // (related to the RPC source) 19 package callinfo 20 21 import ( 22 "html/template" 23 24 "context" 25 ) 26 27 // CallInfo is the extra data stored in the Context 28 type CallInfo interface { 29 // RemoteAddr is the remote address information for this rpc call. 30 RemoteAddr() string 31 32 // Username is associated with this rpc call, if any. 33 Username() string 34 35 // Text is a text version of this connection, as specifically as possible. 36 Text() string 37 38 // HTML represents this rpc call connection in a web-friendly way. 39 HTML() template.HTML 40 } 41 42 // internal type and value 43 type key int 44 45 var callInfoKey key = 0 46 47 // NewContext adds the provided CallInfo to the context 48 func NewContext(ctx context.Context, ci CallInfo) context.Context { 49 return context.WithValue(ctx, callInfoKey, ci) 50 } 51 52 // FromContext returns the CallInfo value stored in ctx, if any. 53 func FromContext(ctx context.Context) (CallInfo, bool) { 54 ci, ok := ctx.Value(callInfoKey).(CallInfo) 55 return ci, ok 56 } 57 58 // HTMLFromContext returns that value of HTML() from the context, or "" if we're 59 // not able to recover one 60 func HTMLFromContext(ctx context.Context) template.HTML { 61 var h template.HTML 62 ci, ok := FromContext(ctx) 63 if ok { 64 return ci.HTML() 65 } 66 return h 67 }