Go 封装http请求包Get、Post

672 次浏览次阅读
没有评论

之前已经封装过 leveldb 包.
今天再把项目中经常会用到的一个技术封装成包,记录下来,仅供需要的小伙伴学习参考 go 如何封装包给别人和自己使用。有需要的小伙伴也可以在自己的项目中直接使用此包。

这里小编以 github 为例 (go 的很多第三方包都在 github 上),其他平台大同小异。

1. 创建仓库

去 github 上创建仓库, 仓库命名为 gorequest

2. 本地创建项目

命名为 gorequest。

注意:因为 go 从 1.11 版本之后开始使用 go mod 管理包的版本。所以这里要想用 go mod 下载你封装的包,要生成 go.mod 文件

go mod init 路径(路径要和你第一步创建的仓库路径保持一致)

mkdir gorequest
go mod init github.com/jeffcail/gorequest

3. 编写代码逻辑

具体代码逻辑可参考我的 GitHub 仓库地址gorequest

4. 上传代码

git init
git add .
git commit -m "first commit"
git branch -M main
git remote add origin git@github.com:jeffcail/gorequest.git
git push -u origin main

Go 封装 http 请求包 Get、Post

5. 设置版本号

进入仓库,点击 Tags, 点击 create new tag 输入版本号,选择输入的版本号。Target 选择对应的分支名称

Go 封装 http 请求包 Get、Post

6. 测试刚才封装的包

创建 demo 项目,并初始化

mkdir demo
go mod init github.com/demo
touch main.go

下载刚才封装的包

go get github.com/jeffcail/gorequest 

代码中使用刚才封装的包发送 get 和 post 请求

main.go

package main

import (
    "fmt"
    "log"

    "github.com/jeffcail/gorequest"
)

func get() {
    url := "https://api.randomuser.me/?nat=US&results=1"
    h := make(map[string]string)
    h["Content-type"] = "application/json"
    p := make(map[string]interface{})
    bytes, err := gorequest.Get(url, h, p)
    if err != nil {log.Fatal(err)
    }
    fmt.Println(string(bytes))
}

func post() {
    url := "http://jsonplaceholder.typicode.com/posts"
    h := make(map[string]string)
    h["Content-type"] = "application/json"
    p := make(map[string]interface{})
    p["userId"] = 1
    p["title"] = " 关于山东为爱出拳 "
    p["body"] = " 千里走单骑 "
    bytes, err := gorequest.Post(url, h, p)
    if err != nil {log.Fatal(err)
    }
    fmt.Println(string(bytes))
}

func main() {fmt.Println("===================================")

    get()

    fmt.Println("===================================")

    post()

    fmt.Println("===================================")
}

7. 完成手工

gorequest项目中可以使用此包发送 get 和 post 请求

此教程觉得有帮助的可以帮忙在上面的 github 地址上点个 star 哦 谢谢帅哥和小姐姐~

正文完
 0
评论(没有评论)