首页
技术小册
AIGC
面试刷题
技术文章
MAGENTO
云计算
视频课程
源码下载
PDF书籍
「涨薪秘籍」
登录
注册
Go搭建一个简单web服务
net/http包使用及工作原理
http客户端
Request
Cookie
Session
Go 日志
处理文件
GO中间件(Middleware )
Redirect 重定向
Golang 下载文件
golang之数据验证validator
Go Redis连接池
Go 函数可变数量参数传参
深入理解nil
指针和内存分配详解
Go 堆栈的理解
Go goroutine理解
GO GC 垃圾回收机制
GO 单例模式
GO 匿名函数和闭包
Go channel 实现原理分析
Go Signal信号处理
Go 并发控制
Go context包的分析
Golang不同类型比较
Go 三个点(…)用法
Golang 跨域
Go 加密解密算法
Go socket实现多语言间通信
grpc的Go服务端和PHP客户端实现
导出mysql表结构生成grpc需要的proto文件工具
Golang 操作Excel文件
vue-element-admin 后台动态加载菜单
gin websocket 一对一聊天
当前位置:
首页>>
技术小册>>
Go开发权威指南(下)
小册名称:Go开发权威指南(下)
示例: **1、实现Get请求方法** ``` package main import ( "fmt" "io/ioutil" "net/http" ) func main() { requestUrl := "http://www.baidu.com" response, err := http.Get(requestUrl) if err != nil { fmt.Println(err) } defer response.Body.Close() body, _ := ioutil.ReadAll(response.Body) fmt.Println(string(body)) } ``` 2、实现post请求方法 ``` package main import ( "bytes" "fmt" "io/ioutil" "net/http" "net/url" ) func main() { requestUrl := "http://www.baidu.com/" postValue := url.Values{ "username": {"aa"}, "address": {"bb"}, "subject": {"cc"}, "form": {"dd"}, } //request, err := http.PostForm(requestUrl, postValue) body := bytes.NewBufferString(postValue.Encode()) request, err := http.Post(requestUrl, "text/html", body) if err != nil { fmt.Println(err) } defer request.Body.Close() fmt.Println(request.StatusCode) if request.StatusCode == 200 { rb, err := ioutil.ReadAll(request.Body) if err != nil { fmt.Println(rb) } fmt.Println(string(rb)) } } ``` 3、 实现PostForm请求方法 ``` package main import ( "fmt" "io/ioutil" "net/url" "net/http" ) func main() { requestUrl := "http://www.baidu.com/" postValue := url.Values{ "username": {"aa"}, "address": {"bb"}, "subject": {"cc"}, "form": {"dd"}, } request, err := http.PostForm(requestUrl, postValue) if err != nil { fmt.Println(err) } defer request.Body.Close() fmt.Println(request.StatusCode) if request.StatusCode == 200 { rb, err := ioutil.ReadAll(request.Body) if err != nil { fmt.Println(rb) } fmt.Println(string(rb)) } } ``` 4、http.Do 使用http.Do方法可以在请求的时候设置头参数、cookie之类的数据。 ``` package main import ( "fmt" "io/ioutil" "net/http" ) func main() { client := &http.Client{} request, err := http.NewRequest("GET", "http://www.baidu.com", nil) if err != nil { fmt.Println(err) } cookie := &http.Cookie{Name: "JERRY", Value: "dkfsf"} request.AddCookie(cookie) //向request中添加cookie //设置request的header request.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") response, err := client.Do(request) if err != nil { fmt.Println(err) return } defer response.Body.Close() fmt.Println(response.StatusCode) if response.StatusCode == 200 { r, err := ioutil.ReadAll(response.Body) if err != nil { fmt.Println(err) } fmt.Println(string(r)) } } ``` 5、json清求 ```` package main import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/url" "strings" ) type Student struct { Name string } func main() { requestUrl:="http://127.0.0.1:8090/" stu := Student{ Name:"lamber", } s,_ := json.Marshal(&stu) HttPJson("GET",requestUrl,s) } func HttPJson(method string, url string, postValue[]byte) ([]byte, error) { body:=bytes.NewBuffer([]byte(postValue)) req, err := http.NewRequest(method, url, body) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") res, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode == http.StatusOK { return nil, errors.New(fmt.Sprintf("response status code %v", res.StatusCode)) } rb, err := ioutil.ReadAll(res.Body) if err != nil { return nil, err } return rb, nil } ```` 6、 PUT请求 ```` package main import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" ) type Student struct { Name string } func main() { requestUrl:="http://127.0.0.1:8090/" stu := Student{ Name:"lamber", } s,_ := json.Marshal(&stu) HttpPut(requestUrl,s) } func HttpPut( url string, params []byte) ([]byte, error) { body := bytes.NewBuffer(params) req, err := http.NewRequest("PUT", url, body) if err != nil { return nil, err } res, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode == http.StatusOK { return nil, errors.New(fmt.Sprintf("response status code %v", res.StatusCode)) } rb, err := ioutil.ReadAll(res.Body) if err != nil { return nil, err } return rb, nil } ```` 7、 delete请求 ```` package main import ( "errors" "fmt" "io/ioutil" "net/http" ) type Student struct { Name string } func main() { requestUrl:="http://127.0.0.1:8090/" HttpDelete(requestUrl) } func HttpDelete( url string) ([]byte, error) { req, err := http.NewRequest("DELETE", url, nil) if err != nil { return nil, err } res, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode == http.StatusOK { return nil, errors.New(fmt.Sprintf("response status code %v", res.StatusCode)) } rb, err := ioutil.ReadAll(res.Body) if err != nil { return nil, err } return rb, nil } ```` 8、上传文件 ```` package main import ( "bytes" "errors" "fmt" "io" "io/ioutil" "mime/multipart" "net/http" "os" ) type Student struct { Name string } func main() { requestUrl:="http://127.0.0.1:8090/upload" path, _ := os.Getwd() path += "/test.txt" extraParams := map[string]string{ "name": "hi", } //extraParams 提交别的参数 res,err:=HttpPostFiles(requestUrl,extraParams,"file",path) fmt.Println(res,err) } func HttpPostFiles(uri string, params map[string]string, paramName, path string) ([]byte, error) { file, err := os.Open(path) if err != nil { return nil, err } defer file.Close() // 实例化multipart body := &bytes.Buffer{} writer := multipart.NewWriter(body) // 创建multipart 文件字段,注意paramName要跟服务端一致 part, err := writer.CreateFormFile(paramName, path) if err != nil { return nil, err } _, err = io.Copy(part, file) for key, val := range params { _ = writer.WriteField(key, val) } err = writer.Close() if err != nil { return nil, err } request, err := http.NewRequest("POST", uri, body) request.Header.Set("Content-Type", writer.FormDataContentType()) res, err := http.DefaultClient.Do(request) if res.StatusCode != http.StatusOK { return nil, errors.New(fmt.Sprintf("response status code %v", res.StatusCode)) } rb, err := ioutil.ReadAll(res.Body) if err != nil { return nil, err } return rb, nil } ````
上一篇:
net/http包使用及工作原理
下一篇:
Request
该分类下的相关小册推荐:
Go 组件设计与实现
Go语言入门实战经典
WebRTC音视频开发实战
深入浅出Go语言核心编程(五)
深入浅出Go语言核心编程(二)
Golang修炼指南
go编程权威指南(四)
Golang并发编程实战
深入浅出Go语言核心编程(三)
深入浅出Go语言核心编程(六)
从零写一个基于go语言的Web框架
深入浅出Go语言核心编程(四)