最近想對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 協議》,轉載必須註明作者和本文連結