vitess.io/vitess@v0.16.2/go/vt/vtadmin/credentials/credentials.go (about) 1 /* 2 Copyright 2021 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 credentials 18 19 import ( 20 "bytes" 21 "encoding/json" 22 "os" 23 "text/template" 24 25 "vitess.io/vitess/go/vt/grpcclient" 26 ) 27 28 // LoadFromTemplate renders a template string into a path, using the data 29 // provided as the template data. It then loads the contents at the resulting 30 // path as a JSON file containing a grpcclient.StaticAuthClientCreds, and 31 // returns both the parsed credentials as well as the concrete path used. 32 func LoadFromTemplate(tmplStr string, data any) (*grpcclient.StaticAuthClientCreds, string, error) { 33 path, err := renderTemplate(tmplStr, data) 34 if err != nil { 35 return nil, "", err 36 } 37 38 creds, err := loadCredentials(path) 39 if err != nil { 40 return nil, "", err 41 } 42 43 return creds, path, nil 44 } 45 46 func renderTemplate(tmplStr string, data any) (string, error) { 47 tmpl, err := template.New("").Parse(tmplStr) 48 if err != nil { 49 return "", err 50 } 51 52 buf := bytes.NewBuffer(nil) 53 if err := tmpl.Execute(buf, data); err != nil { 54 return "", err 55 } 56 57 return buf.String(), nil 58 } 59 60 func loadCredentials(path string) (*grpcclient.StaticAuthClientCreds, error) { 61 data, err := os.ReadFile(path) 62 if err != nil { 63 return nil, err 64 } 65 66 var creds grpcclient.StaticAuthClientCreds 67 if err := json.Unmarshal(data, &creds); err != nil { 68 return nil, err 69 } 70 71 return &creds, nil 72 }