Client
package main
import (
"fmt"
"github.com/parnurzeal/gorequest"
"io/ioutil"
"path/filepath"
)
func main() {
toStruct()
}
// 发送post请求
func httpPost() {
type User struct{NameStructData string}
var user = User{NameStructData:"admin"}
request := gorequest.New()
response, s, errors := request.Post("http://127.0.0.1:5000/post").
// 设置请求头
Set("Content-Type", "application/x-www-form-urlencoded").
// 发送数据
Send(`{"a": "b", "c": "d"}`).
// 发送map数据
SendMap(map[string]interface{}{
"name": "admin",
}).
// 发送结构体数据
SendStruct(user).
End()
if errors != nil {
panic(errors)
}
_ = s
fmt.Println(response.Body)
}
// 发送get请求
func httpGet() {
request := gorequest.New()
response, body, errors := request.Get("http://127.0.0.1:5000/get").
//携带参数
Param("age", "21").
Param("name", "admin").
End()
if errors != nil {
panic(errors)
}
_ = response
fmt.Println(body)
}
// 发送文件
func httpFile() {
f, _ := filepath.Abs("/etc/hosts")
bytesOfFile, _ := ioutil.ReadFile(f)
request := gorequest.New()
response, body, errors := request.Post("http://127.0.0.1:5000/file").
Type("multipart").
// 发送文件
SendFile("./abc.txt").
SendFile(bytesOfFile, "hosts", "file").
End()
if errors != nil {
panic(errors)
}
_ = response
fmt.Println(body)
}
// 发送xml数据
func httpXML() {
request := gorequest.New()
response, body, errors := request.Post("http://127.0.0.1:5000/data").
// 设置请求头
Set("Content-Type", "application/xml").
// 发送xml数据
Send(`<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>`).
End()
if errors != nil{
panic(errors)
}
_ = response
fmt.Println(body)
}
// 返回数据绑定到结构体
func toStruct() {
type User struct{
Name string `json:"name"`
Age int `json:"age"`
}
var user User
request := gorequest.New()
resp, bytes, errors := request.Post("http://127.0.0.1:5000/to_struct").EndStruct(&user)
if errors != nil{
panic(errors)
}
_ = resp
_ = bytes
fmt.Printf("name: %v age: %v\n", user.Name, user.Age)
}
测试Server
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/get')
def httpGet():
print(request.headers)
print('args->', request.args)
return 'ok'
@app.route('/post', methods=['POST'])
def httpPost():
print(request.headers)
print('form->', request.form)
return 'ok'
@app.route('/data', methods=['GET', 'POST'])
def httpData():
print(request.headers)
print('data->', request.data)
return 'ok'
@app.route('/file', methods=['POST'])
def httpFile():
print(request.headers)
print('file', request.files)
return 'ok'
@app.route('/to_struct', methods=['POST'])
def httpToStruct():
return jsonify({'name': 'admin', 'age': 23})
if __name__ == '__main__':
app.run(debug=True)
网友评论