go httptest请求

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())
}
}
posted @   技术颜良  阅读(77)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
历史上的今天:
2022-01-18 vue箭头函数
2022-01-18 要使vue支持ts写法
2022-01-18 为pod设置安全上下文
2022-01-18 vue官网学习
2021-01-18 shell中大于或者等于小于或者等于的写法
2021-01-18 教你在 Centos8 中如何更改运行级别
2021-01-18 k8s学习笔记-调度之Affinity
点击右上角即可分享
微信分享提示