~evanj/cms

ref: 7fc5d7258891c1c58ba07d1e9035517327be7a19 cms/cms.go -rw-r--r-- 1.5 KiB
7fc5d725Evan M Jones WIP(*): Project init. 10 months ago
                                                                                
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// cms is a free and open source content management system.
package main

import (
	"log"
	"net/http"
	"os"
	"strings"

	"git.sr.ht/~evanj/cms/internal/c/ping"
	"git.sr.ht/~evanj/cms/internal/c/space"
	"git.sr.ht/~evanj/cms/internal/c/user"
	"git.sr.ht/~evanj/cms/internal/s/db"
	"git.sr.ht/~evanj/security"
)

var (
	app *App

	port    = os.Getenv("PORT")
	dbtype  = os.Getenv("DBTYPE")
	dbcreds = os.Getenv("DB")
	url     = os.Getenv("URL")
	secret  = os.Getenv("SECRET")
)

type App struct {
	log   *log.Logger
	space http.Handler
	user  http.Handler
	ping  http.Handler
}

func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	parts := strings.Split(r.URL.Path, "/")
	if len(parts) < 2 {
		http.NotFound(w, r)
		return
	}

	switch parts[1] {
	case "ping":
		a.ping.ServeHTTP(w, r)
		return
	case "":
		fallthrough
	case "user":
		a.user.ServeHTTP(w, r)
		return
	case "space":
		a.space.ServeHTTP(w, r)
		return
	}

	http.NotFound(w, r)
}

func init() {
	w := os.Stdout
	applogger := log.New(w, "[cms] ", 0)

	db, err := db.New(
		log.New(w, "[cms:db] ", 0),
		dbtype,
		dbcreds,
		security.Default(secret),
	)
	if err != nil {
		applogger.Fatal(err)
	}

	if err := db.EnsureSetup(); err != nil {
		applogger.Fatal(err)
	}

	app = &App{
		log: applogger,
		space: space.New(
			log.New(w, "[cms:space] ", 0),
			db,
		),
		user: user.New(
			log.New(w, "[cms:user] ", 0),
			db,
		),
		ping: ping.New(
			log.New(w, "[cms:ping] ", 0),
			db,
		),
	}

}

func main() {
	app.log.Println("listening on", url)
	app.log.Fatal(http.ListenAndServe(port, app))
}