123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- package subcmd
- import (
- "fmt"
- "log"
- "net/http"
- "net/url"
- "regexp"
- "strings"
- "time"
- "github.com/alecthomas/kingpin"
- "github.com/codeskyblue/goreq"
- )
- type HTTPHeaderValue http.Header
- func (h *HTTPHeaderValue) Set(value string) error {
- parts := strings.SplitN(value, ":", 2)
- if len(parts) != 2 {
- return fmt.Errorf("expected HEADER:VALUE got '%s'", value)
- }
- (*http.Header)(h).Add(parts[0], parts[1])
- return nil
- }
- func (h *HTTPHeaderValue) String() string {
- return ""
- }
- func (h *HTTPHeaderValue) IsCumulative() bool {
- return true
- }
- func HTTPHeader(s kingpin.Settings) (target *http.Header) {
- target = &http.Header{}
- s.SetValue((*HTTPHeaderValue)(target))
- return
- }
- type HTTPURLValue url.Values
- func (h *HTTPURLValue) Set(value string) error {
- parts := strings.SplitN(value, "=", 2)
- if len(parts) != 2 {
- return fmt.Errorf("expected KEY=VALUE got '%s'", value)
- }
- (*url.Values)(h).Add(parts[0], parts[1])
- return nil
- }
- func (h *HTTPURLValue) String() string {
- return ""
- }
- func (h *HTTPURLValue) IsCumulative() bool {
- return true
- }
- func HTTPValue(s kingpin.Settings) (target *url.Values) {
- target = &url.Values{}
- s.SetValue((*HTTPURLValue)(target))
- return
- }
- var (
- method string
- reqUrl string
- headers *http.Header
- values *url.Values
- bodyData string
- duration time.Duration
- )
- func RegisterCurl(curl *kingpin.CmdClause) {
- curl.Flag("request", "Specify request command to use").Short('X').Default("GET").StringVar(&method)
- curl.Arg("url", "url string").Required().StringVar(&reqUrl)
- curl.Flag("data", "body data").StringVar(&bodyData)
- curl.Flag("timeout", "timeout send and receive response").Default("10s").DurationVar(&duration)
- headers = HTTPHeader(curl.Flag("header", "Add a HTTP header to the request.").Short('H'))
- values = HTTPValue(curl.Flag("form", "Add a HTTP form values").Short('F'))
- }
- func DoCurl() {
- if !regexp.MustCompile(`^https?://`).MatchString(reqUrl) {
- reqUrl = "http://" + reqUrl
- }
- request := goreq.Request{
- Method: method,
- Uri: reqUrl,
- }
- request.ShowDebug = true
- request.Timeout = duration
- for k, values := range *headers {
- for _, v := range values {
- request.AddHeader(k, v)
- }
- }
- if method == "GET" {
- request.QueryString = *values
- } else if method == "POST" {
- request.AddHeader("Content-Type", "application/x-www-form-urlencoded")
- if bodyData != "" {
- request.Body = bodyData
- } else {
- request.Body = *values
- }
- } else {
- log.Fatalf("Unsupported method: %s", method)
- }
- res, err := request.Do()
- if err != nil {
- log.Fatal(err)
- }
- log.Println(res.Body.ToString())
- }
|