~evanj/cms

ref: 356e3f389fe3e9167cffb270f41b6f2b22eb202a cms/cms.go -rw-r--r-- 744 bytes
356e3f38Evan J Feat(context): Completed adding context to data layer. Refactored tests 1 year, 22 days 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
// cms is a free and open source content management system.
package main

import (
	"context"
	"log"
	"net/http"
	"strings"
	"time"
)

type App struct {
	log *log.Logger

	// NOTE: Concurrent read (only) is OK. This is never wrote (but defined on
	// server startup).
	handlers map[string]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
	}

	namespace := parts[1]
	if namespace == "" {
		namespace = "user"
	}

	h, ok := a.handlers[namespace]
	if !ok {
		http.NotFound(w, r)
		return
	}

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	h.ServeHTTP(w, r.WithContext(ctx))
}