1 Star 0 Fork 0

Souki/go-framework

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
run_httpserver_forward.go 1.46 KB
一键复制 编辑 原始数据 按行查看 历史
王少奇 提交于 2021-08-02 17:18 +08:00 . 新增 http转发
package main
import (
"fmt"
v1http "gitee.com/scottq/go-framework/src/v1/httpserver"
v1log "gitee.com/scottq/go-framework/src/v1/log"
"os"
"path/filepath"
"time"
)
func main() {
name := "example"
logPath := fmt.Sprintf("./runtime/logs/%s.log", filepath.Base(os.Args[0]))
logger := v1log.NewZapLog(name, logPath, nil)
httpServer, err := v1http.NewHttpServer("", ":28080")
if err != nil {
logger.Error("run http server error:%s" + err.Error())
return
}
//添加logger
httpServer.AddLogger(logger)
api := &ApiHandler{}
//注册简单的路由
httpServer.RouteGet("/v1", api.Index, nil)
//使用json返回
httpForward := v1http.NewHttpForwardHandler("127.0.0.1:8080/v1/users", time.Second)
httpForward.AddForwardRule(map[string]string{
"/v2/users/*": "127.0.0.1:28080/v1/users",
"/v2/self": "127.0.0.1:28080/v1",
"/v2/file/*/index.html": "127.0.0.1:8080/static",
})
httpServer.RouteHandler("GET", "/v1/users/:uid", httpForward, []v1http.Middleware{
ForwardMiddleware,
})
httpServer.RouteHandler("GET", "/v2/*path", httpForward, []v1http.Middleware{
ForwardMiddleware,
})
logger.Fatal(httpServer.Run().Error())
}
type ApiHandler struct {
}
//http router
func (h *ApiHandler) Index(ctx *v1http.Ctx) {
ctx.Write([]byte("Hello World"))
}
//中间件中设置 自定义response处理器
var ForwardMiddleware v1http.Middleware = func(ctx *v1http.Ctx, next func(*v1http.Ctx)) {
next(ctx)
ctx.Write([]byte("\nforward: " + ctx.Param("uid")))
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/scottq/go-framework.git
git@gitee.com:scottq/go-framework.git
scottq
go-framework
go-framework
v1.1.8

搜索帮助