Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(main): 重构包管理 #19

Merged
merged 5 commits into from
Apr 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 93 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,13 @@ Add and initialize your program and execute it, that's it!
package main

import (
"fmt"
"knife"
"knife/middleware"
"knife/middleware/cache"
"knife/middleware/gzip"
"knife/middleware/logger"
"knife/middleware/proxy"
"knife/middleware/recover"
"log"
"net/http"
"time"
Expand All @@ -43,26 +48,38 @@ func main() {

//Create a middleware chain
//first plan
chain := planOne()
//chain := planOne()

//second plan
//chain := planTwo()

//the third plan
//chain := planThree()

//gzip middleware
//chain := gzipFun()

//cache middleware
//chain := cacheFun()

//cache middleware
chain := loadBalance()

//start serve
_ = http.ListenAndServe(":8080", chain)
err := http.ListenAndServe(":8080", chain)
if err != nil {
panic(err)
}
}

// plan one
func planOne() *knife.Chain {
//create middleware chain
chain := knife.NewChain()
//add logger middleware
chain.Use(middleware.Logger())
chain.Use(logger.Logger())
//add recover middleware
chain.Use(middleware.Recover())
chain.Use(recover.Recover())

//add custom implemented middleware
chain.Use(func(context *knife.Context) {
Expand All @@ -80,7 +97,7 @@ func planOne() *knife.Chain {
// add middleware to the constructor
func planTwo() *knife.Chain {
//create a middleware chain and add logging and error handling middleware
chain := knife.NewChain(middleware.Logger(), middleware.Recover())
chain := knife.NewChain(logger.Logger(), recover.Recover())

//add custom implemented middleware
chain.Use(func(context *knife.Context) {
Expand All @@ -99,8 +116,8 @@ func planTwo() *knife.Chain {
func planThree() *knife.Chain {
//create a middleware chain and use the chain to add logging, error handling, and custom middleware
chain := knife.NewChain().
Use(middleware.Logger()).
Use(middleware.Recover()).
Use(logger.Logger()).
Use(recover.Recover()).
Use(func(context *knife.Context) {
start := time.Now()
defer func() {
Expand All @@ -113,6 +130,74 @@ func planThree() *knife.Chain {
return chain
}

func gzipFun() *knife.Chain {
chain := knife.NewChain().
Use(logger.Logger()).
Use(recover.Recover()).
//Use(middleware.GzipDefault()).
Use(gzip.Gzip(1024)).
Use(func(context *knife.Context) {
data := "Gzip是一种压缩文件格式并且也是一个在类 Unix 上的一种文件解压缩的软件,通常指GNU计划的实现,此处的gzip代表GNU zip。" +
"也经常用来表示gzip这种文件格式。软件的作者是Jean-loup Gailly和Mark Adler。在1992年10月31日第一次公开发布,版本号0.1,1993年2月,发布了1.0版本。" +
"Gzip是一种压缩文件格式并且也是一个在类 Unix 上的一种文件解压缩的软件,通常指GNU计划的实现,此处的gzip代表GNU zip。" +
"也经常用来表示gzip这种文件格式。软件的作者是Jean-loup Gailly和Mark Adler。在1992年10月31日第一次公开发布,版本号0.1,1993年2月,发布了1.0版本。" +
"Gzip是一种压缩文件格式并且也是一个在类 Unix 上的一种文件解压缩的软件,通常指GNU计划的实现,此处的gzip代表GNU zip。" +
"也经常用来表示gzip这种文件格式。软件的作者是Jean-loup Gailly和Mark Adler。在1992年10月31日第一次公开发布,版本号0.1,1993年2月,发布了1.0版本。"
_, err := context.Writer.Write([]byte(data))
if err != nil {
panic(fmt.Sprintf("writer data error %s", err))
}
context.Writer.WriteHeader(http.StatusOK)
})
return chain
}

func cacheFun() *knife.Chain {
chain := knife.NewChain().
Use(logger.Logger()).
Use(recover.Recover()).
Use(cache.Cache(30, 60)).
Use(func(context *knife.Context) {
data := "Hello World"
_, err := context.Writer.Write([]byte(data))
if err != nil {
panic(fmt.Sprintf("writer data error %s", err))
}
context.Writer.WriteHeader(http.StatusOK)
})
return chain
}

func loadBalance() *knife.Chain {
nodes := []*proxy.ServiceNode{
{
Address: "127.0.0.1:8080",
Weight: 1,
},
{
Address: "127.0.0.2:8080",
Weight: 1,
},
{
Address: "127.0.0.3:8080",
Weight: 1,
},
}
chain := knife.NewChain().
Use(logger.Logger()).
Use(recover.Recover()).
Use(proxy.LoadBalanceProxy(proxy.LoadBalanceRandom, nodes)).
Use(func(context *knife.Context) {
data := "Hello World"
_, err := context.Writer.Write([]byte(data))
if err != nil {
panic(fmt.Sprintf("writer data error %s", err))
}
context.Abort(http.StatusOK)
})
return chain
}

```


Expand Down
46 changes: 25 additions & 21 deletions example/base/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ package main
import (
"fmt"
"knife"
"knife/middleware"
"knife/middleware/cache"
"knife/middleware/gzip"
"knife/middleware/logger"
"knife/middleware/proxy"
"knife/middleware/recover"
"log"
"net/http"
"time"
Expand All @@ -22,10 +26,10 @@ func main() {
//chain := planThree()

//gzip middleware
//chain := gzip()
//chain := gzipFun()

//cache middleware
//chain := cache()
//chain := cacheFun()

//cache middleware
chain := loadBalance()
Expand All @@ -42,9 +46,9 @@ func planOne() *knife.Chain {
//create middleware chain
chain := knife.NewChain()
//add logger middleware
chain.Use(middleware.Logger())
chain.Use(logger.Logger())
//add recover middleware
chain.Use(middleware.Recover())
chain.Use(recover.Recover())

//add custom implemented middleware
chain.Use(func(context *knife.Context) {
Expand All @@ -62,7 +66,7 @@ func planOne() *knife.Chain {
// add middleware to the constructor
func planTwo() *knife.Chain {
//create a middleware chain and add logging and error handling middleware
chain := knife.NewChain(middleware.Logger(), middleware.Recover())
chain := knife.NewChain(logger.Logger(), recover.Recover())

//add custom implemented middleware
chain.Use(func(context *knife.Context) {
Expand All @@ -81,8 +85,8 @@ func planTwo() *knife.Chain {
func planThree() *knife.Chain {
//create a middleware chain and use the chain to add logging, error handling, and custom middleware
chain := knife.NewChain().
Use(middleware.Logger()).
Use(middleware.Recover()).
Use(logger.Logger()).
Use(recover.Recover()).
Use(func(context *knife.Context) {
start := time.Now()
defer func() {
Expand All @@ -95,12 +99,12 @@ func planThree() *knife.Chain {
return chain
}

func gzip() *knife.Chain {
func gzipFun() *knife.Chain {
chain := knife.NewChain().
Use(middleware.Logger()).
Use(middleware.Recover()).
//Use(middleware.GzipDefault()).
Use(middleware.Gzip(1024)).
Use(logger.Logger()).
Use(recover.Recover()).
//Use(gzip.Default()).
Use(gzip.Gzip(1024)).
Use(func(context *knife.Context) {
data := "Gzip是一种压缩文件格式并且也是一个在类 Unix 上的一种文件解压缩的软件,通常指GNU计划的实现,此处的gzip代表GNU zip。" +
"也经常用来表示gzip这种文件格式。软件的作者是Jean-loup Gailly和Mark Adler。在1992年10月31日第一次公开发布,版本号0.1,1993年2月,发布了1.0版本。" +
Expand All @@ -117,11 +121,11 @@ func gzip() *knife.Chain {
return chain
}

func cache() *knife.Chain {
func cacheFun() *knife.Chain {
chain := knife.NewChain().
Use(middleware.Logger()).
Use(middleware.Recover()).
Use(middleware.Cache(30, 60)).
Use(logger.Logger()).
Use(recover.Recover()).
Use(cache.Cache(30, 60)).
Use(func(context *knife.Context) {
data := "Hello World"
_, err := context.Writer.Write([]byte(data))
Expand All @@ -134,7 +138,7 @@ func cache() *knife.Chain {
}

func loadBalance() *knife.Chain {
nodes := []*middleware.ServiceNode{
nodes := []*proxy.ServiceNode{
{
Address: "127.0.0.1:8080",
Weight: 1,
Expand All @@ -149,9 +153,9 @@ func loadBalance() *knife.Chain {
},
}
chain := knife.NewChain().
Use(middleware.Logger()).
Use(middleware.Recover()).
Use(middleware.LoadBalanceProxy(middleware.LoadBalanceRandom, nodes)).
Use(logger.Logger()).
Use(recover.Recover()).
Use(proxy.LoadBalanceProxy(proxy.LoadBalanceRandom, nodes)).
Use(func(context *knife.Context) {
data := "Hello World"
_, err := context.Writer.Write([]byte(data))
Expand Down
17 changes: 10 additions & 7 deletions example/matcher/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ package main

import (
"knife"
"knife/matcher"
"knife/middleware"
"knife/matcher/combination"
"knife/matcher/header"
"knife/matcher/path"
"knife/middleware/logger"
"knife/middleware/recover"
"log"
"net/http"
)
Expand All @@ -13,24 +16,24 @@ func main() {
//创建中间件链
chain := knife.NewChain()
//添加日志记录中间件
chain.Use(middleware.Logger())
chain.Use(logger.Logger())
//添加错误处理中间件
chain.Use(middleware.Recover())
chain.Use(recover.Recover())

//添加响应头是否存在匹配器的自定义中间件
chain.UseMatcher(matcher.HeaderResponseExists("token"), func(context *knife.Context) {
chain.UseMatcher(header.ResponseExists("token"), func(context *knife.Context) {
log.Printf("token middleware,token:%s ", context.Writer.Header().Get("token"))
context.Next()
})

//添加带有组合匹配器的自定义中间件
chain.UseMatcher(matcher.Any(matcher.HeaderResponseExists("token"), matcher.HeaderResponseExists("auth")), func(context *knife.Context) {
chain.UseMatcher(combination.Any(header.ResponseExists("token"), header.ResponseExists("auth")), func(context *knife.Context) {
log.Printf("token middleware,token:%s ", context.Writer.Header().Get("token"))
context.Next()
})

//添加带路径匹配器的自定义中间件
chain.UseMatcher(matcher.PathPrefix("/hello"), func(context *knife.Context) {
chain.UseMatcher(path.Prefix("/hello"), func(context *knife.Context) {
log.Println("pathPrefix matcher")
context.Next()
})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// 将匹配器进行组合的匹配器

package matcher
package combination

import "knife"

Expand Down
14 changes: 7 additions & 7 deletions knife/matcher/header.go → knife/matcher/header/header.go
Original file line number Diff line number Diff line change
@@ -1,43 +1,43 @@
// 关于请求头的匹配器

package matcher
package header

import (
"knife"
"net/http"
)

func HeaderResponseExists(key string) knife.MiddlewareMatcher {
func ResponseExists(key string) knife.MiddlewareMatcher {
return func(response knife.HttpResponseWriter, request knife.HttpRequest) bool {
return !equalHeaderValue(response.Header(), key, "")
}
}

func HeaderResponseNotExists(key string) knife.MiddlewareMatcher {
func ResponseNotExists(key string) knife.MiddlewareMatcher {
return func(response knife.HttpResponseWriter, request knife.HttpRequest) bool {
return equalHeaderValue(response.Header(), key, "")
}
}

func HeaderResponseNe(key, value string) knife.MiddlewareMatcher {
func ResponseNe(key, value string) knife.MiddlewareMatcher {
return func(response knife.HttpResponseWriter, request knife.HttpRequest) bool {
return !equalHeaderValue(response.Header(), key, value)
}
}

func HeaderResponseEq(key, value string) knife.MiddlewareMatcher {
func ResponseEq(key, value string) knife.MiddlewareMatcher {
return func(response knife.HttpResponseWriter, request knife.HttpRequest) bool {
return equalHeaderValue(response.Header(), key, value)
}
}

func HeaderRequestExists(key string) knife.MiddlewareMatcher {
func RequestExists(key string) knife.MiddlewareMatcher {
return func(response knife.HttpResponseWriter, request knife.HttpRequest) bool {
return !equalHeaderValue(request.Header, key, "")
}
}

func HeaderRequestNotExists(key string) knife.MiddlewareMatcher {
func RequestNotExists(key string) knife.MiddlewareMatcher {
return func(response knife.HttpResponseWriter, request knife.HttpRequest) bool {
return equalHeaderValue(request.Header, key, "")
}
Expand Down
Loading
Loading