aboutsummaryrefslogtreecommitdiff
path: root/web/server.go
blob: 198cb4442204cf8261021564165abccdd19c2eea (plain) (blame)
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

package web

import (
	"database/sql"
	"net/http"
	"sync"
	"time"

	"github.com/martinlehoux/biking_home/strava"
	"github.com/martinlehoux/kagamigo/kcore"
)

const dateFormat = "2006-01-02"

type Server struct {
	db         *sql.DB
	configPath string

	oauthMu     sync.Mutex
	oauthState  string
	returnToURL string
	syncMu      sync.Mutex
	syncActive  bool
}

type syncClient interface {
	List(from, to time.Time) ([]strava.Activity, error)
	Get(id int64) (strava.Activity, []byte, error)
}

func NewServer(db *sql.DB, configPath string) *Server {
	return &Server{db: db, configPath: configPath}
}

func (s *Server) Handler() http.Handler {
	mux := http.NewServeMux()
	mux.Handle("GET /static/", http.FileServer(http.FS(staticFiles)))
	mux.HandleFunc("GET /", s.handleRides)
	mux.HandleFunc("GET /rides/{id}", s.handleRide)
	mux.HandleFunc("GET /analytics", s.handleAnalytics)
	mux.HandleFunc("POST /rides/{id}/official-climbs", s.handleCreateOfficialClimb)
	mux.HandleFunc("GET /sync", s.handleSyncForm)
	mux.HandleFunc("POST /sync", s.handleSync)
	mux.HandleFunc("GET /strava/login", s.handleStravaLogin)
	mux.HandleFunc("GET /strava/callback", s.handleStravaCallback)
	return kcore.RecoverMiddleware(mux)
}

func (s *Server) ListenAndServe(addr string) error {
	return http.ListenAndServe(addr, s.Handler())
}