-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclient_post.go
96 lines (84 loc) · 2.51 KB
/
client_post.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package client
import (
"fmt"
"github.com/qb0C80aE/clay/extension"
"github.com/spf13/cobra"
"net/url"
)
var clientPostCmd = &cobra.Command{
Use: "post <url>",
Short: "Sends a POST request",
Long: `Sends a POST request to a specified server.`,
PreRunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return fmt.Errorf("invalid argument")
}
if _, err := url.ParseRequestURI(args[0]); err != nil {
return err
}
contentTypeFlagValue := cmd.Flag("content-type").Value.String()
jsonFlagValue := cmd.Flag("json").Value.String()
formFlagValue := cmd.Flag("form").Value.String()
if (contentTypeFlagValue != "json") && (contentTypeFlagValue != "form") {
return fmt.Errorf("invalid content-type")
}
switch contentTypeFlagValue {
case "json":
if len(formFlagValue) > 0 {
return fmt.Errorf("form must not be specified when content-type is json")
}
case "form":
if len(jsonFlagValue) > 0 {
return fmt.Errorf("json must not be specified when content-type is form")
}
default:
return fmt.Errorf("invalid content-type")
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
contentTypeFlagValue := cmd.Flag("content-type").Value.String()
jsonFlagValue := cmd.Flag("json").Value.String()
formFlagValue := cmd.Flag("form").Value.String()
urlArg := args[0]
switch contentTypeFlagValue {
case "json":
content, err := createJSONBody(jsonFlagValue)
if err != nil {
return err
}
response, err := sendRequest(extension.LookUpMethodName(extension.MethodPost),
urlArg,
"application/json",
content)
if err != nil {
return err
}
if err := outputClientResponse(cmd, response); err != nil {
return err
}
case "form":
contentType, content, err := createMultipartFormData(formFlagValue)
if err != nil {
return err
}
response, err := sendRequest(extension.LookUpMethodName(extension.MethodPost),
urlArg,
contentType,
content)
if err != nil {
return err
}
if err := outputClientResponse(cmd, response); err != nil {
return err
}
}
return nil
},
}
func init() {
clientCmd.AddCommand(clientPostCmd)
clientPostCmd.Flags().StringP("content-type", "c", "json", "Content-Type value. 'json' and 'form' are valid")
clientPostCmd.Flags().StringP("json", "j", "", `JSON data like '{"name": "clay", "remark": "tool"}'. Also @filename is available`)
clientPostCmd.Flags().StringP("form", "f", "", "Form value like name=clay,remark=tool. Also key=@filename is available")
}