This repository was archived by the owner on Jun 24, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.go
More file actions
108 lines (95 loc) · 2.4 KB
/
core.go
File metadata and controls
108 lines (95 loc) · 2.4 KB
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
98
99
100
101
102
103
104
105
106
107
108
package a4webbm
import (
"bufio"
"context"
"database/sql"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/sessions"
_ "github.com/mattn/go-sqlite3"
"log"
"net/http"
"os"
"strings"
)
func CoreAdderMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
session := request.Context().Value(ContextValues("session")).(*sessions.Session)
userRef, _ := session.Values["UserRef"].(string)
ctx := context.WithValue(request.Context(), ContextValues("coreData"), &CoreData{
UserRef: userRef,
Title: SiteTitle,
NoFooter: NoFooter,
UseCssColumns: UseCssColumns,
})
next.ServeHTTP(writer, request.WithContext(ctx))
})
}
type CoreData struct {
Title string
AutoRefresh bool
UserRef string
NoFooter bool
UseCssColumns bool
}
type Configuration struct {
data map[string]string
}
// TODO use for settings
func NewConfiguration() *Configuration {
return &Configuration{
data: make(map[string]string),
}
}
func (c *Configuration) set(key, value string) {
c.data[key] = value
}
func (c *Configuration) get(key string) string {
return c.data[key]
}
func (c *Configuration) readConfiguration(filename string) {
file, err := os.Open(filename)
if err != nil {
return
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
log.Printf("File close error: %s", err)
}
}(file)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
sep := strings.Index(line, "=")
if sep >= 0 {
key := line[:sep]
value := line[sep+1:]
c.set(key, value)
}
}
}
type ContextValues string
var (
DbConnectionString = os.Getenv("DB_CONNECTION_STRING")
DbConnectionProvider = os.Getenv("DB_CONNECTION_PROVIDER")
)
func DBAdderMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
db, err := sql.Open(DbConnectionProvider, DbConnectionString)
if err != nil {
log.Printf("error sql init: %s", err)
http.Error(writer, "ERROR", 500)
return
}
defer func(db *sql.DB) {
err := db.Close()
if err != nil {
log.Printf("Error closing db: %s", err)
}
}(db)
ctx := request.Context()
ctx = context.WithValue(ctx, ContextValues("sql.DB"), db)
ctx = context.WithValue(ctx, ContextValues("queries"), New(db))
next.ServeHTTP(writer, request.WithContext(ctx))
})
}