-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmiddleware.go
36 lines (30 loc) · 1.07 KB
/
middleware.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package apiserver
import (
"net/http"
"strings"
"time"
"github.com/mijia/sweb/log"
"github.com/mijia/sweb/server"
"golang.org/x/net/context"
)
// StatWare is the statistics middleware which would log all the access and performation information.
type ReadOnlySwitch struct {
}
// ServeHTTP implements the Middleware interface. Would log all the access, status and performance information.
func (m *ReadOnlySwitch) ServeHTTP(ctx context.Context, w http.ResponseWriter, r *http.Request, next server.Handler) context.Context {
start := time.Now()
e := getEngine(ctx)
if e.ReadOnly() && strings.ToUpper(r.Method) != "GET" &&
!strings.HasPrefix(r.URL.Path, "/api/engine/") {
log.Warnf("Do ReadOnly Request Permitted!, %q %q, duration=%v",
r.Method, r.URL.Path, time.Since(start))
w.WriteHeader(403)
w.Write([]byte("Do ReadOnly Permitted.\n"))
return ctx
}
return next(ctx, w, r)
}
// NewStatWare returns a new StatWare, some ignored urls can be specified with prefixes which would not be logged.
func NewReadOnlySwitch() server.Middleware {
return &ReadOnlySwitch{}
}