github.com/paul-lee-attorney/fabric-ca-1.4.7-gm@v0.0.0-20201120102036-c7ad827cf9ac/util/args.go (about) 1 /* 2 Copyright IBM Corp. 2017 All Rights Reserved. 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 util 18 19 import ( 20 "fmt" 21 "os" 22 ) 23 24 const ( 25 defaultServerProtocol = "http" 26 defaultServerAddr = "localhost" 27 defaultServerPort = "7054" 28 ) 29 30 // GetCommandLineOptValue searches the command line arguments for the 31 // specified option and returns the following value if found; otherwise 32 // it returns "". If **remove** is true and it is found, the option 33 // and its value are removed from os.Args. 34 // For example, if command line is: 35 // fabric-ca client enroll -config myconfig.json 36 // GetCommandLineOptValue("-config",true) returns "myconfig.json" 37 // and changes os.Args to 38 // fabric-ca client enroll 39 func GetCommandLineOptValue(optName string, remove bool) string { 40 for i := 0; i < len(os.Args)-1; i++ { 41 if os.Args[i] == optName { 42 val := os.Args[i+1] 43 if remove { 44 // Splice out the option and its value 45 os.Args = append(os.Args[:i], os.Args[i+2:]...) 46 } 47 return val 48 } 49 } 50 return "" 51 } 52 53 // GetServerURL returns the server's URL 54 func GetServerURL() string { 55 return fmt.Sprintf("%s://%s:%s", GetServerProtocol(), GetServerAddr(), GetServerPort()) 56 } 57 58 // GetServerProtocol returns the server's protocol 59 func GetServerProtocol() string { 60 protocol := GetCommandLineOptValue("-protocol", false) 61 if protocol != "" { 62 return protocol 63 } 64 return defaultServerProtocol 65 } 66 67 // GetServerAddr returns the server's address 68 func GetServerAddr() string { 69 addr := GetCommandLineOptValue("-address", false) 70 if addr != "" { 71 return addr 72 } 73 return defaultServerAddr 74 } 75 76 // GetServerPort returns the server's listening port 77 func GetServerPort() string { 78 port := GetCommandLineOptValue("-port", false) 79 if port != "" { 80 return port 81 } 82 return defaultServerPort 83 } 84 85 // SetDefaultServerPort overrides the default CFSSL server port 86 // by adding the "-port" option to the command line if it was not 87 // already present. 88 func SetDefaultServerPort() { 89 if len(os.Args) > 2 && GetCommandLineOptValue("-port", false) == "" { 90 os.Args = append(os.Args, "-port", defaultServerPort) 91 } 92 }