首页 > 其他分享 >go httptest请求

go httptest请求

时间:2023-01-18 09:11:16浏览次数:47  
标签:Case http 请求 Req httptest func go payload

package test

import (
"encoding/json"
"github.com/cookieY/yee"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"strings"
)

type Case struct {
Method string
Uri string
Handler yee.RestfulAPI
Rec *httptest.ResponseRecorder
Req *http.Request
Yee *yee.Core
}

func (c *Case) Do() *Case {
c.Req.Header.Set("Content-Type", yee.MIMEApplicationJSON)
c.Rec = httptest.NewRecorder()
c.Yee.ServeHTTP(c.Rec, c.Req)
return c
}

func (c *Case) NewTest() {
c.Yee = yee.C()
c.Yee.Restful(c.Uri, c.Handler)
}

func (c *Case) Get(payload string) *Case {
c.Req = httptest.NewRequest(http.MethodGet, c.Uri+payload, nil)
return c
}

func (c *Case) Post(payload string) *Case {
c.Req = httptest.NewRequest(http.MethodPost, c.Uri, strings.NewReader(payload))
return c
}

func (c *Case) Put(payload string) *Case {
c.Req = httptest.NewRequest(http.MethodPut, c.Uri, strings.NewReader(payload))
return c
}

func (c *Case) Delete(payload string) *Case {
c.Req = httptest.NewRequest(http.MethodDelete, c.Uri+payload, nil)
return c
}

func (c *Case) Unmarshal(payload interface{}) {
u, _ := ioutil.ReadAll(c.Rec.Body)
if err := json.Unmarshal(u, &payload); err != nil {
log.Fatal(err.Error())
}
}

标签:Case,http,请求,Req,httptest,func,go,payload
From: https://www.cnblogs.com/cheyunhua/p/17059124.html

相关文章

  • golang实现set
    golang没有原生的set要实现set可以使用map来简易实现定义一个Set可以这么定义typeSet[Tcomparable]struct{setmap[T]struct{}}为什么map的值类型用struct{......
  • django-rest-swagger
    Swagger是一个API开发者的工具框架,用于生成、描述、调用和可视化RESTful风格的Web服务。总体目标是使客户端和文件系统服务器以同样的速度来更新,方法,参数和模型紧密集成到......
  • go 报错汇总
    go报错汇总syntaxerror:non-declarationstatementoutsidefunctionbody我是这样写的,谷歌搜了一下说是运算需要放在main函数里(我是初学go^_^)。packagemainimp......
  • Django接入Swagger,生成Swagger接口文档-操作解析
        Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的Web服务。总体目标是使客户端和文件系统源代码作为服务器以同样的速度来更新。当......
  • go 锁
    Gosync包提供了两种锁类型:互斥锁sync.Mutex和读写互斥锁sync.RWMutex,都属于悲观锁。概念:Mutex是互斥锁,当一个goroutine获得了锁后,其他goroutine不能获取锁(只能存......
  • brew install mongodb
    admin@admindeMac-mini/%[email protected]......
  • hugo 安装使用
    安装go先在https://go.dev/doc/install下载压缩包,然后进行安装rm-rf/usr/local/go&&tar-C/usr/local-xzfgo1.19.5.linux-amd64.tar.gzexportPATH=$PATH:/us......
  • 我的Go+语言初体验——在Docker建立一个可以用Go+语言开发的容器环境(以Ubuntu容器为例
    前言​​“我的Go+语言初体验”|征文活动进行中......​​作为一名嵌入式软件工程师的我,在工作中使用高级语言开发的场景不多,但技术的迭代大部分偏向于应用层开发,身为程序......
  • go 使用redis
       import(redigo"github.com/gomodule/redigo/redis")  funcNewPool()*redigo.Pool{//return&redigo.Pool{//MaxIdle:3,......
  • golang无缓冲channel避坑点
    输出结果顺序:默认情况下,channel接收和发送数据都是阻塞的,除非另一端已经准备好。......