测试 iris 时自定义 context 包

最近想对iris写好的做做测试,结果由于内部方法(包括获取session)基本都需要context,查看了底层相关实现写了个简单封装自定义的iris.context的方法,不多说先上代码

package test

import (
    "github.com/kataras/iris"
    "github.com/kataras/iris/context"
    "io"
    "net/http"
    "strconv"
)

type onlyrepw http.Header
func (ho onlyrepw) Header() http.Header {
    return http.Header(ho)
}

func (ho onlyrepw) Write([]byte) (int, error) {
    panic("NOIMPL")
}

func (ho onlyrepw) WriteHeader(int) {
    panic("NOIMPL")
}

/*
    body like strings.NewReader("z=post&both=y&prio=2&=nokey&orphan;empty=&") OR strings.NewReader("")
    method like "GET"
    url like "http://www.baidu.com?z=aaa"
 */
func getContext(method string,url string,body io.Reader)context.Context  {
    ap:=iris.New()

    ctx:=context.NewContext(ap)

    //構造responsewriter
    m := make(http.Header)
    repw:=onlyrepw(m)

    //構造requset
    request, err := http.NewRequest(method, url, body)
    if err!=nil {
        panic(err)
    }

    cookie := &http.Cookie{Name: "maple", Value: strconv.Itoa(123)}
    request.AddCookie(cookie)
    ctx.ResetRequest(request)

    ctx.BeginRequest(repw,request)
    return ctx
}

这只是个大概的思路,要是有更好的方式可以欢迎留言

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!