-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathserver.go
74 lines (61 loc) · 2.05 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
69
70
71
72
73
74
package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/gorilla/mux"
"github.com/kelseyhightower/envconfig"
"github.com/kshitij10496/hercules/common"
"github.com/kshitij10496/hercules/services/course"
"github.com/kshitij10496/hercules/services/department"
"github.com/kshitij10496/hercules/services/faculty"
"github.com/kshitij10496/hercules/services/migration"
_ "github.com/lib/pq"
)
func main() {
var config common.Config
if err := envconfig.Process("hercules", &config); err != nil {
fmt.Fprintln(os.Stderr, err)
envconfig.Usage("hercules", &config)
os.Exit(1)
}
// Create a new router
mainRouter := mux.NewRouter()
// Create the subrouter which handles all the API calls
servicesRouter := mainRouter.PathPrefix(common.VERSION).Subrouter()
// List all the services
servers := map[string]common.Server{
"service-course": course.NewServiceCourse(),
"service-department": department.NewServiceDepartment(),
"service-faculty": faculty.NewServiceFaculty(),
"service-migration": migration.NewServiceMigration(),
}
// Connect each service with the DB and add them to the subrouters
for name, server := range servers {
log.Printf("%s creating...\n", name)
err := server.ConnectDB(config.Database)
if err != nil {
log.Fatalf("Error connecting with DB for %s: %v\n", name, err)
}
servicesRouter.PathPrefix(server.GetURL()).Handler(server)
log.Printf("%s created!\n", name)
}
// TODO: Handle services page and home page
staticPath := common.VERSION + "/static/"
staticHandler := http.StripPrefix(staticPath, http.FileServer(http.Dir("./static")))
mainRouter.PathPrefix(staticPath).Handler(staticHandler)
log.Printf("Server starting on %v\n", config.Port)
if err := http.ListenAndServe(":"+config.Port, mainRouter); err != nil {
for name, server := range servers {
log.Printf("%s closing...\n", name)
err := server.CloseDB()
if err != nil {
log.Fatalf("Error closing DB for %s: %v\n", name, err)
}
log.Printf("%s closed!\n", name)
}
log.Printf("Server cannot be started!\n")
log.Fatal(err)
}
}