aboutsummaryrefslogtreecommitdiff
path: root/pkg/handler/router.go
blob: 82ee8fdc32a068b111399bd610fddc7496dd90d2 (plain)
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
package handler

import (
	"net/http"

	serverconfig "git.gabrielgio.me/cerrado/pkg/config"
	"git.gabrielgio.me/cerrado/pkg/ext"
	"git.gabrielgio.me/cerrado/pkg/handler/about"
	"git.gabrielgio.me/cerrado/pkg/handler/auth"
	"git.gabrielgio.me/cerrado/pkg/handler/git"
	"git.gabrielgio.me/cerrado/pkg/handler/static"
	"git.gabrielgio.me/cerrado/pkg/service"
)

// Mount handler gets the requires service and repository to build the handlers
// This functons wraps the whole handler package and wraps it into one part so
// its sub package don't leak in other places.
func MountHandler(
	gitService *service.GitService,
	authService *service.AuthService,
	configRepo *serverconfig.ConfigurationRepository,
) (http.Handler, error) {
	var (
		gitHandler   = git.NewGitHandler(gitService, configRepo)
		aboutHandler = about.NewAboutHandler(configRepo)
		loginHandler = auth.NewLoginHandler(authService)
	)

	staticHandler, err := static.ServeStaticHandler()
	if err != nil {
		return nil, err
	}

	mux := ext.NewRouter()
	mux.AddMiddleware(ext.Compress)
	mux.AddMiddleware(ext.Log)

	if configRepo.IsAuthEnabled() {
		mux.AddMiddleware(ext.Authenticate(authService))
		mux.HandleFunc("/login/{$}", loginHandler.Login)
		mux.HandleFunc("/logout/{$}", loginHandler.Logout)
	} else {
		mux.AddMiddleware(ext.DisableAuthentication)
	}

	mux.HandleFunc("/static/{file}", staticHandler)
	mux.HandleFunc("/{name}/about/{$}", gitHandler.About)
	mux.HandleFunc("/{name}/", gitHandler.Summary)
	mux.HandleFunc("/{name}/refs/{$}", gitHandler.Refs)
	mux.HandleFunc("/{name}/tree/{ref}/{rest...}", gitHandler.Tree)
	mux.HandleFunc("/{name}/blob/{ref}/{rest...}", gitHandler.Blob)
	mux.HandleFunc("/{name}/log/{ref}/", gitHandler.Log)
	mux.HandleFunc("/{name}/commit/{ref}/", gitHandler.Commit)
	mux.HandleFunc("/{name}/archive/{file}", gitHandler.Archive)
	mux.HandleFunc("/about", aboutHandler.About)
	mux.HandleFunc("/", gitHandler.List)
	return mux.Handler(), nil
}