forked from grafana/k6
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
79 lines (67 loc) · 2.24 KB
/
server.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
*
* k6 - a next-generation load testing tool
* Copyright (C) 2016 Load Impact
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package api
import (
"fmt"
"net/http"
"github.com/sirupsen/logrus"
"github.com/urfave/negroni"
"github.com/loadimpact/k6/api/common"
v1 "github.com/loadimpact/k6/api/v1"
"github.com/loadimpact/k6/core"
)
func NewHandler() http.Handler {
mux := http.NewServeMux()
mux.Handle("/v1/", v1.NewHandler())
mux.Handle("/ping", HandlePing())
mux.Handle("/", HandlePing())
return mux
}
func ListenAndServe(addr string, engine *core.Engine) error {
mux := NewHandler()
n := negroni.New()
n.Use(negroni.NewRecovery())
n.UseFunc(WithEngine(engine))
n.UseFunc(NewLogger(logrus.StandardLogger()))
n.UseHandler(mux)
return http.ListenAndServe(addr, n)
}
// NewLogger returns the middleware which logs response status for request.
func NewLogger(l *logrus.Logger) negroni.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
next(rw, r)
res := rw.(negroni.ResponseWriter)
l.WithField("status", res.Status()).Debugf("%s %s", r.Method, r.URL.Path)
}
}
func WithEngine(engine *core.Engine) negroni.HandlerFunc {
return negroni.HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
r = r.WithContext(common.WithEngine(r.Context(), engine))
next(rw, r)
})
}
func HandlePing() http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Add("Content-Type", "text/plain; charset=utf-8")
if _, err := fmt.Fprint(rw, "ok"); err != nil {
logrus.WithError(err).Error("Error while printing ok")
}
})
}