forked from shibukawa/curl_as_dsl
/
main.go
60 lines (53 loc) · 1.53 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"github.com/gopherjs/gopherjs/js"
"github.com/jessevdk/go-flags"
"github.com/shibukawa/curl_as_dsl/common"
"github.com/shibukawa/curl_as_dsl/generator"
"github.com/shibukawa/optstring_parser"
"honnef.co/go/js/console"
"html"
"strings"
)
type GlobalOptions struct{}
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 := optstring_parser.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 "", ""
}
func main() {
js.Global.Set("CurlAsDsl", map[string]interface{}{
"generate": GenerateCode,
})
}