Ai
1 Star 0 Fork 0

dale/公共包

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
internal.go 2.29 KB
一键复制 编辑 原始数据 按行查看 历史
dale 提交于 2021-12-01 18:44 +08:00 . 增加mapv的copy函数
package httpsvr
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/http/httptest"
"net/http/httputil"
"time"
"gitee.com/daledi/public/options"
"gitee.com/daledi/public/vmap"
"github.com/pkg/errors"
)
type HttpTest struct {
Router *Router
OPT options.GlobalOPT
IsSimple bool
Valid bool
}
func NewTest(conf string) HttpTest {
ht := HttpTest{
OPT: options.GOPT(),
Router: NewRouter("", nil),
IsSimple: true,
Valid: true,
}
var err error
if ht.OPT, err = options.ReadConfig(conf); err != nil {
log.Fatalf("Cant read test.conf: %v\n", err)
}
// router := httpsvr.NewRouter("", nil)
ht.Router.Prefix = ht.OPT.Prefix
ht.Router.ErrLog = ht.OPT.ErrLog
ht.Router.ResponseHandler = func(ctx *Context) {
if ctx.Response == nil {
ctx.Response = 9999
}
//econf.LogDebug("[Defer] Response: %v\n", ctx.Response)
fmt.Printf("耗时:%s\n", time.Since(ctx.Begin).String())
// switch v := ctx.Response.(type) {
// case int:
// msg := NewRespMsg(v)
// ctx.Writer.Header().Set("X-Code", strconv.Itoa(v))
// ctx.Response = msg.Bytes()
// ctx.ContextType = TypeJson
// }
}
ht.Router.PanicHandler = func(ctx *Context) {
if err := recover(); err != nil {
gConf := ctx.Keys["conf"].(options.GlobalOPT)
httprequest, _ := httputil.DumpRequest(ctx.Req, false)
gConf.ErrLog.Printf("[Recovery] Request: %s\n", string(httprequest))
gConf.ErrLog.Printf("[Recovery] Error: %s\n", fmt.Sprintf("%+v", errors.Errorf("%v", err)))
ctx.Writer.WriteHeader(http.StatusInternalServerError)
}
}
return ht
}
func (ht HttpTest) HttpApiTest(req *http.Request) {
res := httptest.NewRecorder()
// req, _ := http.NewRequest("PUT", "/gfc/globalsumdata/v2", bytes.NewReader(data))
// req.Header.Set("X-Token", "test")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Real-IP", "127.0.0.1")
ht.Router.ServeHTTP(res, req)
fmt.Printf("%s %s response:\n", req.Method, req.URL.Path)
// formatOut(res.Body, isSimple)
r := res.Result()
fmt.Printf("Status: %s\n", r.Status)
var tt vmap.V
if err := json.Unmarshal(res.Body.Bytes(), &tt); err != nil {
fmt.Printf("err: %v\n", err)
}
if ht.IsSimple {
fmt.Printf("%v: %s\n", tt["code"], tt.VString("message"))
return
}
cc, _ := json.MarshalIndent(tt, "", " ")
fmt.Printf("Body: %s\n", string(cc))
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/daledi/public.git
git@gitee.com:daledi/public.git
daledi
public
公共包
v1.0.0

搜索帮助