MCPcopy
hub / github.com/writefreely/writefreely / Web

Method Web

handle.go:487–548  ·  view source on GitHub ↗

Web handles requests made in the web application. This provides user- friendly HTML pages and actions that work in the browser.

(f handlerFunc, ul UserLevelFunc)

Source from the content-addressed store, hash-verified

485// Web handles requests made in the web application. This provides user-
486// friendly HTML pages and actions that work in the browser.
487func (h *Handler) Web(f handlerFunc, ul UserLevelFunc) http.HandlerFunc {
488 return func(w http.ResponseWriter, r *http.Request) {
489 h.handleHTTPError(w, r, func() error {
490 var status int
491 start := time.Now()
492
493 defer func() {
494 if e := recover(); e != nil {
495 u := getUserSession(h.app.App(), r)
496 username := "None"
497 if u != nil {
498 username = u.Username
499 }
500 log.Error("User: %s\n\n%s: %s", username, e, debug.Stack())
501 log.Info("Web deferred internal error render")
502 h.errors.InternalServerError.ExecuteTemplate(w, "base", pageForReq(h.app.App(), r))
503 status = 500
504 }
505
506 log.Info(h.app.ReqLog(r, status, time.Since(start)))
507 }()
508
509 if ul(h.app.App().cfg) != UserLevelNoneType {
510 session, err := h.sessionStore.Get(r, cookieName)
511 if err != nil && (ul(h.app.App().cfg) == UserLevelNoneRequiredType || ul(h.app.App().cfg) == UserLevelUserType) {
512 // Cookie is required, but we can ignore this error
513 log.Error("Handler: Unable to get session (for user permission %d); ignoring: %v", ul(h.app.App().cfg), err)
514 }
515
516 _, gotUser := session.Values[cookieUserVal].(*User)
517 if ul(h.app.App().cfg) == UserLevelNoneRequiredType && gotUser {
518 to := correctPageFromLoginAttempt(r)
519 log.Info("Handler: Required NO user, but got one. Redirecting to %s", to)
520 err := impart.HTTPError{http.StatusFound, to}
521 status = err.Status
522 return err
523 } else if ul(h.app.App().cfg) == UserLevelUserType && !gotUser {
524 log.Info("Handler: Required a user, but DIDN'T get one. Sending not logged in.")
525 err := ErrNotLoggedIn
526 status = err.Status
527 return err
528 }
529 }
530
531 // TODO: pass User object to function
532 err := f(h.app.App(), w, r)
533 if err == nil {
534 status = 200
535 } else if httpErr, ok := err.(impart.HTTPError); ok {
536 status = httpErr.Status
537 } else {
538 e := fmt.Sprintf("[Web handler] 500: %v", err)
539 log.Error(e)
540 log.Info("Web internal error render")
541 h.errors.InternalServerError.ExecuteTemplate(w, "base", pageForReq(h.app.App(), r))
542 status = 500
543 }
544

Callers 5

PageMethod · 0.95
InitRoutesFunction · 0.80
RouteCollectionsFunction · 0.80
RouteReadFunction · 0.80

Calls 7

handleHTTPErrorMethod · 0.95
getUserSessionFunction · 0.85
pageForReqFunction · 0.85
AppMethod · 0.65
ReqLogMethod · 0.65
fFunction · 0.50

Tested by

no test coverage detected