Go 封装http请求包Get、Post

作者: 太阳上的雨天 分类: Go 发布时间: 2022-11-12 02:40

之前已经封装过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

image-20221112025221955

5. 设置版本号

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

image-20221112024532987

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哦 谢谢帅哥和小姐姐~

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注