72 lines
1.5 KiB
Go
72 lines
1.5 KiB
Go
package requests
|
|
|
|
import "net/url"
|
|
|
|
// Workflow 工作流
|
|
type Workflow struct {
|
|
session *Session
|
|
URL string
|
|
Method string
|
|
Body *Params
|
|
Query map[string][]string
|
|
}
|
|
|
|
// NewWorkflow new and init workflow
|
|
func NewWorkflow(ses *Session) *Workflow {
|
|
wf := &Workflow{}
|
|
wf.SwitchSession(ses)
|
|
return wf
|
|
}
|
|
|
|
// SwitchSession 替换Session
|
|
func (wf *Workflow) SwitchSession(ses *Session) {
|
|
wf.session = ses
|
|
}
|
|
|
|
// SetParams 参数设置
|
|
func (wf *Workflow) SetParams(params ...interface{}) *Workflow {
|
|
plen := len(params)
|
|
defaultContentType := TypeURLENCODED
|
|
|
|
if plen >= 2 {
|
|
t := params[plen-1]
|
|
defaultContentType = t.(string)
|
|
wf.Body.ContentType = defaultContentType
|
|
} else {
|
|
wf.Body.ContentType = defaultContentType
|
|
}
|
|
|
|
if defaultContentType == TypeFormData {
|
|
// TODO: form-data
|
|
createMultipart(wf.Body, params)
|
|
} else {
|
|
var values url.Values
|
|
switch param := params[0].(type) {
|
|
case map[string]string:
|
|
values := make(url.Values)
|
|
for k, v := range param {
|
|
values.Set(k, v)
|
|
}
|
|
wf.Body.Body = []byte(values.Encode())
|
|
case map[string][]string:
|
|
values = param
|
|
wf.Body.Body = []byte(values.Encode())
|
|
case string:
|
|
wf.Body.Body = []byte(param)
|
|
case []byte:
|
|
wf.Body.Body = param
|
|
}
|
|
}
|
|
return wf
|
|
}
|
|
|
|
// Execute 执行
|
|
func (wf *Workflow) Execute() (*Response, error) {
|
|
req := buildBodyRequest(wf.Method, wf.URL, wf.Body)
|
|
resp, err := wf.session.client.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return FromHTTPResponse(resp)
|
|
}
|