当前位置:网站首页>Goframe day 4

Goframe day 4

2022-06-13 03:48:00 shelgi

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 ).

image-20220608082337208

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())
	}

}

image-20220608092836546

image-20220608092904486

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())
	}

image-20220608095115501

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()
}

image-20220608115754167

image-20220608123506681

image-20220608133732490

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
原网站

版权声明
本文为[shelgi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206130335373851.html