aboutsummaryrefslogtreecommitdiffstats
path: root/main.go
blob: 4f34f663397d4e2a5aa6a7151f0d7da104ada40c (plain)
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
package main

import (
	"database/sql"
	"encoding/hex"
	"fmt"
	"html/template"
	"log"
	"net/http"
	"net/http/httputil"

	"github.com/gorilla/securecookie"
)

type handler func(DataStore, http.ResponseWriter, *http.Request)

type App struct {
	DataStore
	DB            *sql.DB
	Config        *Config
	CookieHandler *securecookie.SecureCookie
	Template      *template.Template
}

func New() *App {
	app := new(App)
	config := NewConfig()
	app.Config = config
	db, err := sql.Open("postgres", config.Database)
	if err = db.Ping(); err != nil {
		log.Fatal(err)
	}
	app.DB = db
	app.DataStore = &SqlStore{db}
	hashKey, err := hex.DecodeString(config.HashKey)
	blockKey, err := hex.DecodeString(config.HashKey)
	s := securecookie.New(hashKey, blockKey)
	app.CookieHandler = s
	fmap := template.FuncMap{
		"ago": ago,
	}
	templates := template.Must(template.New("").Funcs(fmap).ParseGlob("templates/*.tmpl"))
	app.Template = templates
	return app
}

func logg(fn http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		d, _ := httputil.DumpRequest(r, true)
		fmt.Printf("--------------------------\n%s\n", d)
		r.ParseForm()
		fn(w, r)
	}
}

func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	app := New()

	go func() {
		sm := http.NewServeMux()
		sm.HandleFunc("/", logg(app.mainHandler))
		sm.HandleFunc("/np", logg(app.nowPlayingHandler))
		sm.HandleFunc("/scrobble", logg(app.scrobbleHandler))
		//http.HandleFunc("/2.0/", logg(app.ApiHandler))
		http.ListenAndServe(":3001", sm)
	}()

	app.TrackInfo("believe", "cher")

	sm := http.NewServeMux()
	fs := http.FileServer(http.Dir("static"))
	sm.Handle("/static/", http.StripPrefix("/static/", fs))
	sm.HandleFunc("/", app.root)
	sm.HandleFunc("/callback", app.callback)
	sm.HandleFunc("/login", app.login)
	sm.HandleFunc("/settings", app.settings)
	http.ListenAndServe(":8000", sm)
}