Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
93 lines (80 loc) · 2 KB
/
Copy pathmain.go
File metadata and controls
93 lines (80 loc) · 2 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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"path"
"strings"
"github.com/fluidkeys/teamserver/models"
_ "github.com/lib/pq"
)
const (
host = "localhost"
port = 5432
user = "teamserver"
dbname = "teamserver_development"
)
var (
password = os.Getenv("TEAMSERVER_PASSWORD")
)
// Env provides a way to hook into the database
type Env struct {
db models.Datastore
TeamsHandler *TeamsHandler
}
func (env *Env) ServeHTTP(res http.ResponseWriter, req *http.Request) {
var head string
head, req.URL.Path = shiftPath(req.URL.Path)
if head == "teams" {
env.TeamsHandler.ServeHTTP(res, req, env.db)
return
}
http.Error(res, "Not Found", http.StatusNotFound)
}
func main() {
db, err := models.NewDB(connStr())
if err != nil {
log.Panic(err)
}
env := &Env{db, new(TeamsHandler)}
err = http.ListenAndServe(Port(), env)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
// Port retrieves the port from the environment so we can run on Heroku
func Port() string {
var port = os.Getenv("PORT")
// Set a default port if there is nothing in the environment
if port == "" {
port = "4747"
fmt.Println("INFO: No PORT environment variable detected, defaulting to " + port)
}
return ":" + port
}
func connStr() string {
herokuDatabaseURL, present := os.LookupEnv("DATABASE_URL")
if present {
return herokuDatabaseURL
}
return fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
}
func formatAsJSONMessage(message string) string {
bytes, _ := json.Marshal(map[string]string{"message": message})
return string(bytes)
}
// ShiftPath splits off the first component of p, which will be cleaned of
// relative components before processing. head will never contain a slash and
// tail will always be a rooted path without trailing slash.
func shiftPath(p string) (head, tail string) {
p = path.Clean("/" + p)
i := strings.Index(p[1:], "/") + 1
if i <= 0 {
return p[1:], "/"
}
return p[1:i], p[i:]
}