good morning!!!!

Skip to content
Snippets Groups Projects
Commit f5d6c24c authored by a's avatar a
Browse files

remove cli

parent d894b581
No related branches found
No related tags found
No related merge requests found
// Code generated by go-openrpc. DO NOT EDIT.
package main
import "github.com/gregdhill/go-openrpc/cmd"
func main() {
cmd.Execute()
}
// Code generated by go-openrpc. DO NOT EDIT.
package cmd
import (
"strconv"
"strings"
"errors"
"fmt"
"log"
"github.com/spf13/cobra"
"net/http"
"io/ioutil"
"bytes"
"os"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
rpct "github.com/gregdhill/go-openrpc/rpc"
"encoding/json"
)
var cfgFile string
var rpcAddr string
{{- $cliName := programName }}
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "{{ $cliName }}",
Short: "{{ .Info.Title }} CLI",
Long: `This is an auto-generated CLI interface for an Open-RPC compliant API.
Open-RPC Version: {{ .Info.Version }}
Run '{{ $cliName }} completion --help' to learn about auto-auto-completion! It's easy!
`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}
// completionCmd represents the completion command
var completionCmd = &cobra.Command{
Use: "completion",
Short: "Generates bash completion scripts",
Long: `To load completion run
. <({{ $cliName }} completion)
To configure your bash shell to load completions for each session add to your bashrc
# ~/.bashrc or ~/.profile
. <({{ $cliName }} completion)
`,
Run: func(cmd *cobra.Command, args []string) {
rootCmd.GenBashCompletion(os.Stdout);
},
}
var errJSONRPC = errors.New("json rpc did return error")
func makeJSONRPCRequest(name string, params []byte) ([]byte, error) {
reqBody := rpct.RPCRequest{
JSONRPC: "2.0",
Method: name,
Params: params,
ID: os.Getpid(), // TODO
}
reqBod, err := json.Marshal(reqBody)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", rpcAddr, bytes.NewBuffer(reqBod))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode != 200 {
err = errors.New("request errored")
return body, err
}
errResponse := rpct.RPCErrorResponse{}
err = json.Unmarshal(body, &errResponse)
if err != nil {
return body, err
}
if errResponse.Error != nil {
// Did get error response from server.
return body, errJSONRPC
}
return body, nil
}
func handleJSONRPCResponse(body []byte, err error) {
fmt.Println(string(body))
if err == nil {
os.Exit(0)
}
if err == errJSONRPC {
os.Exit(1)
}
os.Exit(2)
}
// marshalParams returns a JSONified map or array
// If any of the values contain an "=", then a map will
// be used.
// When using a map, if not ALL values contain an =,
// then an error will be thrown.
func marshalParams(params []string) ([]byte, error) {
paramsMapT := make(map[string]interface{})
paramsArrayT := []interface{}{}
if len(params) == 0 {
return json.Marshal(paramsArrayT)
}
useArray := true
for _, a := range params {
if strings.Contains(a, "=") {
useArray = false
break
}
}
for _, a := range params {
if !useArray && !strings.Contains(a, "=") {
return nil, errors.New("invalid params - when using '=' syntax for an object parameter, all values must be of the format key=value")
}
var key, val string
if !useArray {
kv := strings.Split(a, "=")
if len(kv) != 2 {
return nil, errors.New("invalid params, syntax be k=v, got: " + a)
}
key, val = kv[0], kv[1]
} else {
val = a
}
if vint, err := strconv.Atoi(val); err == nil {
paramsMapT[key] = vint
paramsArrayT = append(paramsArrayT, vint)
} else if vbool, err := strconv.ParseBool(val); err == nil {
paramsMapT[key] = vbool
paramsArrayT = append(paramsArrayT, vbool)
} else {
paramsMapT[key] = val
paramsArrayT = append(paramsArrayT, val)
}
}
/*
if verbose {
log.Println("request", )
}
*/
if useArray {
return json.Marshal(paramsArrayT)
}
return json.Marshal(paramsMapT)
}
{{ $components := .Components }}
{{ range .Methods }}
{{ $paramsLength := (len .Params) }}
var {{ .Name | camelCase | lowerFirst }}Cmd = &cobra.Command{
Use: "{{ .Name }}",
Short: "{{ .Summary }}",
Long: `
Params: {{ if eq (len .Params) 0 }}<NONE>
{{ else}}
{{- range $index, $element := .Params }}
{{- $d := lookupContentDescriptor $components $element }}
- ({{$index}}):{{if $d.Required }} [Required] {{end}}<{{ $d.Name }}>
{{ derefSchema $components $element.Schema | schemaAsJSONPretty | sanitizeBackticks }}
{{- end }}
{{ end -}}
Returns:
{{- $r := lookupContentDescriptor $components .Result }}
{{ derefSchema $components $r.Schema | schemaAsJSONPretty | sanitizeBackticks }}
{{- if ne .ExternalDocs.URL ""}}
For more information see {{- printf "%s" .ExternalDocs.Description }}: {{- printf "%s" .ExternalDocs.URL }}
{{- end}}
`,
{{if .Deprecated -}}
Deprecated: "DEPRECATED: Use at your own risk.",
PreRun: func(cmd *cobra.Command, args []string) {
log.Println("WARNING: This method ({{.Name}}) is deprecated. Use at your own risk.")
},
{{- end }}
Run: func(cmd *cobra.Command, args []string) {
// len params: {{ $paramsLength }}
params, err := marshalParams(args)
if err != nil {
log.Fatalln(err)
}
body, err := makeJSONRPCRequest("{{.Name}}", params)
handleJSONRPCResponse(body, err)
},
}
{{- end }}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
cobra.OnInitialize(initConfig)
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
{{- $defaultAddr := "http://localhost:8545" }}
{{- if gt (len .Servers) 0 }}
{{- $serverZ := slice .Servers 0 }}
{{- $defaultAddr = $serverZ.URL }}
{{- end }}
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ $cliName }}.yaml)")
rootCmd.PersistentFlags().StringVar(&rpcAddr, "http-addr", "{{ $defaultAddr }}", "Address for JSON-RPC HTTP calls")
// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
rootCmd.AddCommand(completionCmd)
{{- range .Methods }}
rootCmd.AddCommand({{.Name | camelCase | lowerFirst }}Cmd)
{{- end }}
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Search config in home directory with name ".{{ $cliName }}" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".{{ $cliName }}")
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment