1 Star 0 Fork 0

Wsage/go-framework

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
run_httpserver.go 2.20 KB
一键复制 编辑 原始数据 按行查看 历史
王少奇 提交于 2021-08-28 09:26 . 优化
package main
import (
"fmt"
v1http "gitee.com/scottq/go-framework/src/v1/httpserver"
v1log "gitee.com/scottq/go-framework/src/v1/log"
"net/http"
"os"
"path/filepath"
)
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("", ":40001")
if err != nil {
logger.Error("run http server error:%s" + err.Error())
return
}
//添加logger
httpServer.AddLogger(logger)
//注册简单的路由
mids := []v1http.Middleware{
v1http.GlobalMiddlewareCorsMiddleware(nil),
v1http.GlobalMiddlewarePanic,
v1http.GlobalMiddlewareAddRequestId("RequestId"),
//v1http.GlobalMiddlewareCorsMiddleware(nil),
v1http.GlobalMiddlewareOptionRequest,
v1http.GlobalMiddlewareQPSLimiter(100, 100),
}
handler := &HttpApiHandler{}
httpServer.RouteHandler("GET","/",handler,mids)
httpServer.RouteHandler("POST", "/", handler, mids)
httpServer.RouteHandler("OPTIONS","/",handler,mids)
//
//api := &ApiHandler{}
//httpServer.RouteGet("/", api.Index, mids)
//httpServer.RoutePost("/", api.Index, mids)
//httpServer.RouteOptions("/", api.Index, mids)
//httpServer.RouteGet("/v1", api.Index, nil)
//
////使用json返回
//httpServer.RouteGet("/v1/users", api.Users, nil)
//httpServer.RoutePost("/v1/exception", api.Exception, nil)
//httpServer.RouteOptions("/v1/exception", api.Exception, nil)
//httpServer.RouteDelete("/v1/exception", api.Exception, nil)
//httpServer.RoutePut("/v1/exception", api.Exception, nil)
//httpServer.RouteFiles("/static", http.Dir("public"))
logger.Fatal(httpServer.Run().Error())
}
type HttpApiHandler struct {
}
func (h *HttpApiHandler) ServeHTTP(w http.ResponseWriter, request *http.Request) {
w.Write([]byte("Hello Handler"))
}
type ApiHandler struct {
}
//http router
func (h *ApiHandler) Index(ctx *v1http.Ctx) {
ctx.Write([]byte("Hello World"))
}
func (h *ApiHandler) Users(ctx *v1http.Ctx) {
users := []map[string]interface{}{
{"uid": 1, "username": "jack"},
{"uid": 2, "username": "lucy"},
}
ctx.SetData(users)
ctx.SetMsg("success")
ctx.Response()
}
func (h *ApiHandler) Exception(ctx *v1http.Ctx) {
ctx.WriteHeader(500)
ctx.Response()
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/scottq/go-framework.git
git@gitee.com:scottq/go-framework.git
scottq
go-framework
go-framework
v1.1.25

搜索帮助