Skip to content

Commit

Permalink
feat: add basic middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
zjregee committed Aug 17, 2024
1 parent d1e55dc commit 634de9a
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 3 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/code_check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: stable
go-version: 1.22.0

- name: Install Dependencies
run: |
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/e2e_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: stable
go-version: 1.22.0

- name: Install Dependencies
run: |
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/unit_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: stable
go-version: 1.22.0

- name: Install Dependencies
run: |
Expand Down
17 changes: 17 additions & 0 deletions ahttp/middleware/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package middleware

import (
"fmt"

"github.com/zjregee/anet/ahttp"
)

func Logger() ahttp.MiddlewareFunc {
return func(next ahttp.HandlerFunc) ahttp.HandlerFunc {
return func(c *ahttp.Context) (returnErr error) {
returnErr = next(c)
fmt.Printf("[MIDDLEWARE LOGGER]: %s %s %v\n", c.Request().Method, c.Request().URL.Path, returnErr)
return
}
}
}
34 changes: 34 additions & 0 deletions ahttp/middleware/recovery.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package middleware

import (
"fmt"
"net/http"
"runtime"

"github.com/zjregee/anet/ahttp"
)

const stackSize = 4 * 1024
const disableStackAll = false

func Recover() ahttp.MiddlewareFunc {
return func(next ahttp.HandlerFunc) ahttp.HandlerFunc {
return func(c *ahttp.Context) (returnErr error) {
defer func() {
if r := recover(); r != nil {
err, ok := r.(error)
if !ok {
err = fmt.Errorf("%v", r)
}
stack := make([]byte, stackSize)
len := runtime.Stack(stack, !disableStackAll)
stack = stack[:len]
fmt.Printf("[MIDDLEWARE PANIC RECOVER]: %v %s\n", err, stack)
c.Response().WriteHeader(http.StatusInternalServerError)
_, returnErr = c.Response().Write(nil)
}
}()
return next(c)
}
}
}

0 comments on commit 634de9a

Please sign in to comment.