func main() { var globalOptions GlobalOptions var curlOptions common.CurlOptions curlOptions.Init() parser := flags.NewParser(&globalOptions, flags.Default) curlCommand, err := parser.AddCommand("curl", "Generate code from curl options", "This command has almost same options of curl and generate code", &curlOptions) urls, err := parser.Parse() if err != nil { os.Exit(1) } if len(urls) > 1 { fmt.Println("It accept only one url. Remained urls are ignored.") } if parser.Active == curlCommand { // --url option has higher priority than params. if curlOptions.Url == "" { if len(urls) > 0 { curlOptions.Url = urls[0] } else { log.Fatalln("Both --url option and url parameters are missing") } } sourceCode, langName, templateName, option := generator.GenerateCode(globalOptions.Target, &curlOptions) if templateName != "" { if globalOptions.Debug { st := reflect.TypeOf(option) v := reflect.ValueOf(option) fmt.Fprintf(os.Stderr, "Debug: template name=%s_%s\n", langName, templateName) fmt.Fprintf(os.Stderr, "Debug: template context=%s\n", st.Name()) num := st.NumField() for i := 0; i < num; i++ { fmt.Fprintf(os.Stderr, " %s: %s\n", st.Field(i).Name, v.Field(i).String()) } } fmt.Println(sourceCode) } else { PrintLangHelp(globalOptions.Target) os.Exit(1) } } }
func GenerateCode(target, options string) (string, string) { var globalOptions GlobalOptions var curlOptions common.CurlOptions curlOptions.Init() parser := flags.NewParser(&globalOptions, flags.Default) curlCommand, err := parser.AddCommand("curl", "Generate code from curl options", "This command has almost same options of curl and generate code", &curlOptions) if !strings.HasPrefix(options, "curl ") { options = "curl " + options } args := shell.Parse(options) urls, err := parser.ParseArgs(args) if err != nil { console.Log(err) return "", err.Error() } if len(urls) > 1 { return "", "It accept only one url. Remained urls are ignored:" + strings.Join(urls, ", ") } if parser.Active == curlCommand { // --url option has higher priority than params. if curlOptions.Url == "" { if len(urls) > 0 { curlOptions.Url = urls[0] } else { console.Error("Both --url option and url parameters are missing") return "", "Both --url option and url parameters are missing" } } sourceCode, _, _, _ := generator.GenerateCode(target, &curlOptions) return html.EscapeString(sourceCode), "" } return "", "" }