Skip to content

Commit 2377fd7

Browse files
author
JojiiOfficial
committed
improve code quality
Disable keepalive function
1 parent 575f9a4 commit 2377fd7

10 files changed

Lines changed: 59 additions & 76 deletions

File tree

Dockerfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
FROM golang:1.14.1-alpine3.11 as builder1
2+
FROM golang:1.14.2-alpine as builder1
33

44
# Setting up environment for builder1
55
ENV GO111MODULE=on

handlers/AuthHandler.go

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,40 +6,44 @@ import (
66
"strings"
77
)
88

9+
/*
10+
The AuthHandler is a wrapper for supported Authorization mechanisms. Currently
11+
Only Bearer token are supported which are provided by an "Authorization" header inside the request
12+
*/
13+
914
var (
10-
//ErrorTokenInvalid error if token is invalid
15+
// ErrorTokenInvalid error if token is invalid
1116
ErrorTokenInvalid error = errors.New("Token invalid")
12-
//ErrorTokenEmpty error if token is empty
13-
ErrorTokenEmpty error = errors.New("Token empty")
1417
)
1518

16-
//AuthHandler handler for http auth
19+
// AuthHandler handler for http auth
1720
type AuthHandler struct {
1821
Request *http.Request
1922
}
2023

21-
//NewAuthHandler returns a new AuthHandler
24+
// NewAuthHandler returns a new AuthHandler
2225
func NewAuthHandler(request *http.Request) *AuthHandler {
2326
return &AuthHandler{
2427
Request: request,
2528
}
2629
}
2730

28-
//GetBearer return the bearer token
31+
// GetBearer return the bearer token
2932
func (authHandler AuthHandler) GetBearer() string {
3033
authHeader, has := authHandler.Request.Header["Authorization"]
31-
//Validate bearer token
34+
// Validate bearer token
3235
if !has || len(authHeader) == 0 || !strings.HasPrefix(authHeader[0], "Bearer") {
3336
return ""
3437
}
3538
return tokenFromBearerHeader(authHeader[0])
3639
}
3740

41+
// Parse the Authorization header and return its real value (the token)
3842
func tokenFromBearerHeader(header string) string {
3943
return strings.TrimSpace(strings.ReplaceAll(header, "Bearer", ""))
4044
}
4145

42-
//IsInvalid return true if err is invalid
46+
// IsInvalid return true if err is invalid
4347
func (authHandler AuthHandler) IsInvalid(err error) bool {
4448
return err == ErrorTokenInvalid
4549
}

handlers/FileAttrHandler.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@ import (
1010
"github.com/jinzhu/gorm"
1111
)
1212

13-
//AttributeHandler handler for attributes
13+
// AttributeHandler handler for file attributes.
14+
// Implements update, delete, get and create functions
15+
// for tags and groups
1416
func AttributeHandler(handlerData web.HandlerData, w http.ResponseWriter, r *http.Request) {
1517
// Get vars
1618
vars := mux.Vars(r)
@@ -250,7 +252,6 @@ func UserAttributeHandler(handlerData web.HandlerData, w http.ResponseWriter, r
250252
return
251253
}
252254

253-
// create map
254255
nsMap := make(map[string][]models.Group)
255256

256257
// Create map with namespace as key

handlers/FileHandler.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,7 @@ func FileHandler(handlerData web.HandlerData, w http.ResponseWriter, r *http.Req
405405
},
406406
Name: request.Name,
407407
Namespace: namespace,
408+
// TODO add group/tag filter
408409
})
409410

410411
if LogError(err) {

handlers/NamespaceHandler.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,6 @@ func NamespaceActionHandler(handlerData web.HandlerData, w http.ResponseWriter,
108108
return
109109
}
110110

111-
// Send success
112111
sendResponse(w, models.ResponseSuccess, "", models.StringResponse{
113112
String: namespace.Name,
114113
})

handlers/PingHandler.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77
"github.com/DataManager-Go/DataManagerServer/models"
88
)
99

10-
//Ping handles ping request
10+
// Ping handles ping request
1111
func Ping(handlerData web.HandlerData, w http.ResponseWriter, r *http.Request) {
1212
var request models.PingRequest
1313
if !readRequestLimited(w, r, &request, handlerData.Config.Webserver.MaxRequestBodyLength) {

handlers/Responses.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ func handleAndSendError(err error, w http.ResponseWriter, message string, status
1212
if !LogError(err) {
1313
return false
1414
}
15+
1516
sendResponse(w, models.ResponseError, message, nil, statusCode)
1617
return true
1718
}

handlers/Router.go

Lines changed: 31 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package handlers
33
import (
44
"fmt"
55
"net/http"
6-
"net/http/pprof"
76
"time"
87

98
"github.com/DataManager-Go/DataManagerServer/handlers/web"
@@ -16,7 +15,7 @@ import (
1615
log "github.com/sirupsen/logrus"
1716
)
1817

19-
//Route for REST
18+
// Route for REST
2019
type Route struct {
2120
Name string
2221
Method HTTPMethod
@@ -25,10 +24,10 @@ type Route struct {
2524
HandlerType requestType
2625
}
2726

28-
//HTTPMethod http method. GET, POST, DELETE, HEADER, etc...
27+
// HTTPMethod http method. GET, POST, DELETE, HEADER, etc...
2928
type HTTPMethod string
3029

31-
//HTTP methods
30+
// HTTP methods
3231
const (
3332
GetMethod HTTPMethod = "GET"
3433
POSTMethod HTTPMethod = "POST"
@@ -44,13 +43,13 @@ const (
4443
optionalTokenRequest
4544
)
4645

47-
//Routes all REST routes
46+
// Routes all REST routes
4847
type Routes []Route
4948

50-
//RouteFunction function for handling a route
49+
// RouteFunction function for handling a route
5150
type RouteFunction func(web.HandlerData, http.ResponseWriter, *http.Request)
5251

53-
//Routes
52+
// Routes
5453
var (
5554
routes = Routes{
5655
// Ping
@@ -147,10 +146,11 @@ var (
147146
HandlerFunc: NamespaceListHandler,
148147
HandlerType: sessionRequest,
149148
},
149+
// TODO add stats
150150
}
151151
)
152152

153-
//NewRouter create new router
153+
// NewRouter create new router and its required components
154154
func NewRouter(config *models.Config, db *gorm.DB) *mux.Router {
155155
handlerData := web.HandlerData{
156156
Config: config,
@@ -166,30 +166,13 @@ func NewRouter(config *models.Config, db *gorm.DB) *mux.Router {
166166
Handler(RouteHandler(route.HandlerType, &handlerData, route.HandlerFunc, route.Name))
167167
}
168168

169-
//Adding custom routes
169+
// Adding custom routes
170170
addCustomRoutes(router, &handlerData)
171171

172-
// Add profiler func if profiling is enabled
173-
if config.Webserver.Profiling {
174-
addProfilerFuncs(router)
175-
}
176-
177172
return router
178173
}
179174

180-
// add pprof funcs
181-
func addProfilerFuncs(router *mux.Router) {
182-
router.HandleFunc("/debug/pprof/", pprof.Index)
183-
router.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
184-
router.HandleFunc("/debug/pprof/profile", pprof.Profile)
185-
router.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
186-
router.Handle("/debug/pprof/heap", pprof.Handler("heap"))
187-
router.Handle("/debug/pprof/goroutine", pprof.Handler("goroutine"))
188-
router.Handle("/debug/pprof/block", pprof.Handler("block"))
189-
router.Handle("/debug/pprof/threadcreate", pprof.Handler("threadcreate"))
190-
}
191-
192-
//Add custom web-routes
175+
// Add custom web-routes
193176
func addCustomRoutes(router *mux.Router, handlerData *web.HandlerData) {
194177
// 404 Handler
195178
router.NotFoundHandler = RouteHandler(defaultRequest, handlerData, web.NotFoundHandler, "not found")
@@ -204,18 +187,17 @@ func addCustomRoutes(router *mux.Router, handlerData *web.HandlerData) {
204187
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./html/static"))))
205188
}
206189

207-
//RouteHandler logs stuff
190+
// RouteHandler logs stuff
208191
func RouteHandler(requestType requestType, handlerData *web.HandlerData, inner RouteFunction, name string) http.Handler {
209192
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
210193
defer func() {
211-
err := r.Body.Close()
212-
if err != nil {
194+
if err := r.Body.Close(); err != nil {
213195
log.Info(err)
214196
}
215197
}()
216198

199+
// Only debug routes which have a names
217200
needDebug := len(name) > 0
218-
219201
if needDebug {
220202
log.Infof("[%s] %s\n", r.Method, name)
221203
}
@@ -226,33 +208,41 @@ func RouteHandler(requestType requestType, handlerData *web.HandlerData, inner R
226208
return
227209
}
228210

229-
//Validate request by requestType
211+
// Validate request by requestType
230212
if !requestType.validate(handlerData, r, w) {
231213
return
232214
}
233215

234-
//Process request
216+
// Process request
235217
inner(*handlerData, w, r)
236218

237-
//Print duration of processing
219+
// Print duration of processing
238220
if needDebug {
239221
printProcessingDuration(start)
240222
}
241223
})
242224
}
243225

244-
//Return false on error
226+
// Validate the given request based on its requestType
227+
// if validate returns false, the request has to abort
245228
func (requestType requestType) validate(handlerData *web.HandlerData, r *http.Request, w http.ResponseWriter) bool {
246229
switch requestType {
247230
case sessionRequest:
248231
{
232+
// SessionRequest requires a valid session token
233+
// which identifies a specific user
234+
235+
// Create an AuthHandler using r
249236
authHandler := NewAuthHandler(r)
237+
238+
// Check Token validity by its length
250239
if len(authHandler.GetBearer()) != 64 {
251240
log.Error("Invalid token len %d", len(authHandler.GetBearer()))
252241
sendResponse(w, models.ResponseError, "Invalid token", http.StatusUnauthorized)
253242
return false
254243
}
255244

245+
// Try to retrieve the user by the requestToken
256246
user, err := models.GetUserFromSession(handlerData.Db, authHandler.GetBearer())
257247
if LogError(err) || user == nil {
258248
if user == nil && err == nil {
@@ -263,14 +253,16 @@ func (requestType requestType) validate(handlerData *web.HandlerData, r *http.Re
263253
return false
264254
}
265255

256+
// Set the handlerData.User which is
257+
// required by all endpoint functions
266258
handlerData.User = user
267259
}
268260
}
269261

270262
return true
271263
}
272264

273-
//Prints the duration of handling the function
265+
// Prints the duration of handling the function
274266
func printProcessingDuration(startTime time.Time) {
275267
dur := time.Since(startTime)
276268

@@ -281,13 +273,13 @@ func printProcessingDuration(startTime time.Time) {
281273
}
282274
}
283275

284-
//Return true on error
276+
// Return true on error
285277
func validateHeader(config *models.Config, w http.ResponseWriter, r *http.Request) bool {
286278
headerSize := gaw.GetHeaderSize(r.Header)
287279

288-
//Send error if header are too big. MaxHeaderLength is stored in b
280+
// Send error if header are too big. MaxHeaderLength is stored in b
289281
if headerSize > uint32(config.Webserver.MaxHeaderLength) {
290-
//Send error response
282+
// Send error response
291283
w.WriteHeader(http.StatusRequestEntityTooLarge)
292284
fmt.Fprint(w, "413 request too large")
293285

handlers/UserHandler.go

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,7 @@ import (
99
"github.com/JojiiOfficial/gaw"
1010
)
1111

12-
//Login login handler
13-
//-> /user/login
12+
// Login login handler
1413
func Login(handlerData web.HandlerData, w http.ResponseWriter, r *http.Request) {
1514
var request models.CredentialsRequest
1615

@@ -44,8 +43,7 @@ func Login(handlerData web.HandlerData, w http.ResponseWriter, r *http.Request)
4443
}
4544
}
4645

47-
//Register register handler
48-
//-> /user/create
46+
// Register register handler
4947
func Register(handlerData web.HandlerData, w http.ResponseWriter, r *http.Request) {
5048
if !handlerData.Config.Server.AllowRegistration {
5149
sendResponse(w, models.ResponseError, "Server doesn't accept registrations", nil, http.StatusForbidden)

services/APIService.go

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ func NewAPIService(config *models.Config, db *gorm.DB) *APIService {
3737
WriteTimeout: config.Webserver.WriteTimeout,
3838
IdleTimeout: 0 * time.Second,
3939
}
40+
41+
httpServer.SetKeepAlivesEnabled(false)
4042
}
4143

4244
//Init https server
@@ -48,6 +50,8 @@ func NewAPIService(config *models.Config, db *gorm.DB) *APIService {
4850
WriteTimeout: config.Webserver.WriteTimeout,
4951
IdleTimeout: 0 * time.Second,
5052
}
53+
54+
httpsServer.SetKeepAlivesEnabled(false)
5155
}
5256

5357
apiService := &APIService{
@@ -60,9 +64,9 @@ func NewAPIService(config *models.Config, db *gorm.DB) *APIService {
6064
return apiService
6165
}
6266

63-
//Start the API service
67+
// Start the API service
6468
func (service *APIService) Start() {
65-
//Start HTTPS if enabled
69+
// Start HTTPS if enabled
6670
if service.HTTPTLSServer != nil {
6771
log.Infof("Server started TLS on port (%s)\n", service.config.Webserver.HTTPS.ListenAddress)
6872
go (func() {
@@ -74,7 +78,7 @@ func (service *APIService) Start() {
7478
})()
7579
}
7680

77-
//Start HTTP if enabled
81+
// Start HTTP if enabled
7882
if service.HTTPServer != nil {
7983
log.Infof("Server started HTTP on port (%s)\n", service.config.Webserver.HTTP.ListenAddress)
8084
go (func() {
@@ -86,20 +90,3 @@ func (service *APIService) Start() {
8690
})()
8791
}
8892
}
89-
90-
// ConnContext: func(ctx context.Context, c net.Conn) context.Context {
91-
// connectionCancel, cancelWriteTimeout := context.WithCancel(ctx)
92-
// go func() {
93-
// defer cancelWriteTimeout()
94-
// _ = <-connectionCancel.Done()
95-
// if err := connectionCancel.Err(); err == context.DeadlineExceeded {
96-
// fmt.Println("a")
97-
// c.Close()
98-
// }
99-
// }()
100-
// return context.WithValue(ctx, ctx.Value(http.ServerContextKey), cancelWriteTimeout)
101-
// },
102-
// if f, ok := ctx.Value(ctx.Value(http.ServerContextKey)).(context.CancelFunc); ok {
103-
// f()
104-
// }
105-
// // sendResponse(w, models.ResponseError, "timeout", nil, http.StatusRequestTimeout)

0 commit comments

Comments
 (0)