当前位置:网站首页>Goframe day 4
Goframe day 4
2022-06-13 03:48:00 【shelgi】
List of articles
GoFrame day4
Preface
Last time there was a hole left , That is the upload part of the file . Today HTTP The client part of
HTTPClient
have access to gclient.New()
Create a client object , You can also use g.Client()
Method call create object ( In fact, it means returning gclient.New()
The object of ).
there gclient
In fact, it also encapsulates http.Client
, The client also provides a series of request methods , But the request result object needs to be used after it is used Close()
close
Chain operation
GoFrame The client supports chain operation , That is, multiple methods can be called in a chain
In this place, you can take a look at the examples on the official website
Basic use
A simple example of using client requests
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/os/gfile"
)
var ctx = gctx.New()
func main() {
if r, err := g.Client().Get(ctx, "https://goframe.org"); err != nil {
panic(err)
} else {
defer r.Close()
fmt.Println(r.ReadAllString())
}
if r, err := g.Client().Get(ctx, "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png"); err != nil {
panic(err)
} else {
defer r.Close()
gfile.PutBytes("./tmp/baidu.png", r.ReadAll())
}
}
To test the client post
request , First write a simple service
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
type RegisterReq struct {
Name string
Pass string `p:"password"`
Pass2 string `p:"password-confirm"`
}
type RegisterRes struct {
Code int `json:"code"`
Error string `json:"error"`
Data any `json:"data"`
}
func main() {
s := g.Server()
s.BindHandler("/data/*", func(r *ghttp.Request) {
var req *RegisterReq
if err := r.Parse(&req); err != nil {
r.Response.WriteJsonExit(RegisterRes{
Code: 1,
Error: err.Error(),
})
}
r.Response.WriteJsonExit(RegisterRes{
Data: req,
})
})
s.SetPort(8080)
s.Run()
}
Then try again post
To pass in data
if r, err := g.Client().Post(
ctx,
"http://localhost:8080/data",
`{"name":"shelgi","password":"123456","password-confirm":"123456"}`,
); err != nil {
panic(err)
} else {
defer r.Close()
fmt.Println(r.ReadAllString())
}
Upload files
Finally began to fill the previous pit , File upload can be divided into single file upload, multi file upload and form file upload . If we want to limit the file type , Then we need to use regularity to judge .
Upload the server
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
// Upload uploads files to /tmp .
func Upload(r *ghttp.Request) {
files := r.GetUploadFiles("upload-file")
names, err := files.Save("./tmp/")
if err != nil {
r.Response.WriteExit(err)
}
println(names)
r.Response.WriteExit("upload successfully: ", names)
}
// UploadShow shows uploading simgle file page.
func UploadShow(r *ghttp.Request) {
r.Response.Write(` <html> <head> <title>GF Upload File Demo</title> </head> <body> <form enctype="multipart/form-data" action="/upload" method="post"> <input type="file" name="upload-file" /> <input type="submit" value="upload" /> </form> </body> </html> `)
}
// UploadShowBatch shows uploading multiple files page.
func UploadShowBatch(r *ghttp.Request) {
r.Response.Write(` <html> <head> <title>GF Upload Files Demo</title> </head> <body> <form enctype="multipart/form-data" action="/upload" method="post"> <input type="file" name="upload-file" multiple="multiple"/> <input type="submit" value="upload" /> </form> </body> </html> `)
}
func main() {
s := g.Server()
s.Group("/upload", func(group *ghttp.RouterGroup) {
group.POST("/", Upload)
group.ALL("/show", UploadShow)
group.ALL("/batch", UploadShowBatch)
})
s.SetPort(8080)
s.Run()
}
uploadFiles
Type is a slice , And you can look at some of them Save
Method , It can save a single file and multiple files .
client
When the client uploads files, it only needs to use ghttp.Post()
, Where the parameters are Property name [email protected]: route
Set up Cookie\Header\Proxy
It has been completely encapsulated in the corresponding Setxxx
In the method , Just modify the settings as needed
Print request information
http
Client support for HTTP Requested input and output raw information acquisition and printing , Convenient debugging , The relevant methods are as follows :
func (r *Response) Raw() string
func (r *Response) RawDump()
func (r *Response) RawRequest() string
func (r *Response) RawResponse() string
边栏推荐
- Determine whether the file encoding format is UTF-8 or GBK
- 【面试复习】自用不定时更新
- 单片机:PCF8591 应用程序
- 【MySQL】索引与事务
- 不卷了!团队又一位成员离职了。。
- Doris outputs numbers in currency format. The integer part is separated by commas every three digits, and the decimal part is reserved for two digits
- 学生管理系统
- Alibaba cloud keep on record
- Lambda终结操作查找与匹配allMatch
- LVS four layer load balancing cluster (5) LVS overview
猜你喜欢
不卷了!团队又一位成员离职了。。
【测试开发】用例篇
微信扫描二维码无法下载文件的解决办法
【测试开发】自动化测试selenium(三)——unittest框架解析
Synching build your own synchronization cloud
【测试开发】测试的相关基本概念
单片机:A/D(模数转换)的主要指标
SQL injection case demonstration and preventive measures
Install cnpm and use cnpm command in vscode terminal
在JDBC连接数据库时报错:Connection to 139.9.130.37:15400 refused.
随机推荐
UDP connection map collection
Get to know druid IO real time OLAP data analysis storage system
2022春学期总结
Stream流的注意事项
LeetCode 178. Score ranking (MySQL)
Installing MySQL 8.0.20 under Linux and ubuntu20.04 LTS
基于PHP的轻量数码商城系统
On interests and hobbies
测试写入mysql数据300W条,每次1.6-2W之间就断掉然后出现以下问题:
H5 jump to mobile app store
Doris data import broker load
Oracle database management
LVS four layer load balancing cluster (4) main methods of load balancing
单片机:EEPROM 多字节读写操作时序
LVS four layer load balancing cluster (5) LVS overview
【测试开发】自动化测试selenium篇(一)
单片机:A/D(模数转换)的主要指标
【多线程】多线程到底是个甚——多线程初阶(复习自用)
单片机:I2C通信协议讲解
Lambda终结操作查找与匹配findAny