/
server.go
68 lines (60 loc) · 1.76 KB
/
server.go
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
package main
import (
"./models"
"./routes"
//"log"
"net/http"
"regexp"
"strings"
"github.com/go-martini/martini"
"github.com/go-gorp/gorp"
)
// The one and only martini instance.
var m *martini.Martini
func init() {
m = martini.New()
// Setup middleware
m.Use(martini.Recovery())
m.Use(martini.Logger())
m.Use(martini.Static("public"))
m.Use(MapEncoder)
// Setup routes
r := martini.NewRouter()
// Inject database
m.MapTo(models.Dbm, (*gorp.SqlExecutor)(nil))
// Add the router action
m.Action(r.Handle)
}
// The regex to check for the requested format (allows an optional trailing
// slash).
var rxExt = regexp.MustCompile(`(\.(?:xml|text|json))\/?$`)
// MapEncoder intercepts the request's URL, detects the requested format,
// and injects the correct encoder dependency for this request. It rewrites
// the URL to remove the format extension, so that routes can be defined
// without it.
func MapEncoder(c martini.Context, w http.ResponseWriter, r *http.Request) {
// Get the format extension
matches := rxExt.FindStringSubmatch(r.URL.Path)
ft := ".json"
if len(matches) > 1 {
// Rewrite the URL without the format extension
l := len(r.URL.Path) - len(matches[1])
if strings.HasSuffix(r.URL.Path, "/") {
l--
}
r.URL.Path = r.URL.Path[:l]
ft = matches[1]
}
// Inject the requested encoder
switch ft {
case ".text":
c.MapTo(routes.TextEncoder{}, (*routes.Encoder)(nil))
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
default:
c.MapTo(routes.JsonEncoder{}, (*routes.Encoder)(nil))
w.Header().Set("Content-Type", "application/json")
}
}
func main() {
m.Run()
}