-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
79 lines (66 loc) · 2.42 KB
/
main.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
75
76
77
78
79
package main
import (
"fmt"
"log"
"net/http"
"github.com/aiden0z/go-jwt-middleware"
"github.com/dgrijalva/jwt-go"
"github.com/facebookgo/inject"
"github.com/gorilla/mux"
"github.com/jessevdk/go-flags"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/hirondelle-app/api/api"
"github.com/hirondelle-app/api/common"
"github.com/hirondelle-app/api/tweets"
"github.com/hirondelle-app/api/users"
)
func init() {
_, err := flags.Parse(&common.Config)
if err != nil {
panic(err)
}
}
func main() {
db := initDatabase()
jwtMiddleware := initJwtMiddleware()
tweetsHandlers := &api.TweetsHandlers{}
authMiddleware := &api.AuthMiddleware{}
tweetsManager := &tweets.Manager{}
usersManager := &users.Manager{}
if err := inject.Populate(db, jwtMiddleware, tweetsHandlers, authMiddleware, tweetsManager, usersManager); err != nil {
panic(err)
}
router := mux.NewRouter()
// public routes
router.Handle("/tweets", http.HandlerFunc(tweetsHandlers.GetTweetsEndpoint)).Methods("GET")
router.HandleFunc("/keywords", tweetsHandlers.GetAllKeywordsEndpoint).Methods("GET")
router.HandleFunc("/keywords/{keywordID}/tweets", tweetsHandlers.GetTweetsByKeywordEndpoint).Methods("GET")
// admin routes
router.Handle("/keywords", authMiddleware.Use(http.HandlerFunc(tweetsHandlers.PostKeywordEndpoint))).Methods("POST")
router.Handle("/keywords/{keywordID}", authMiddleware.Use(http.HandlerFunc(tweetsHandlers.DeleteKeywordEndpoint))).Methods("DELETE")
router.Handle("/tweets/{tweetID}", authMiddleware.Use(http.HandlerFunc(tweetsHandlers.DeleteTweetEndpoint))).Methods("DELETE")
fmt.Printf("Starting server on port %v\n", common.Config.ServerPort)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", common.Config.ServerPort), router))
}
func initDatabase() *gorm.DB {
db, err := gorm.Open("postgres",
fmt.Sprintf("host=%s user=%s dbname=%s password=%s sslmode=disable",
common.Config.Database.Address,
common.Config.Database.Username,
common.Config.Database.Name,
common.Config.Database.Password))
if err != nil {
panic("failed to connect database")
}
db.AutoMigrate(&tweets.Tweet{}, &tweets.Keyword{}, &users.User{})
return db
}
func initJwtMiddleware() *jwtmiddleware.JWTMiddleware {
return jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte(common.Config.Auth0Secret), nil
},
SigningMethod: jwt.SigningMethodHS256,
})
}