@@ -3,7 +3,6 @@ package handlers
33import (
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
2019type 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...
2928type HTTPMethod string
3029
31- //HTTP methods
30+ // HTTP methods
3231const (
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
4847type Routes []Route
4948
50- //RouteFunction function for handling a route
49+ // RouteFunction function for handling a route
5150type RouteFunction func (web.HandlerData , http.ResponseWriter , * http.Request )
5251
53- //Routes
52+ // Routes
5453var (
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
154154func 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
193176func 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
208191func 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
245228func (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
274266func 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
285277func 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
0 commit comments