main.go 5.75 KB
Newer Older
Vasiliy's avatar
Vasiliy committed
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package main

import (
	"encoding/json"
	"os"

	"github.com/golang-migrate/migrate/v4"
	"github.com/golang-migrate/migrate/v4/database/postgres"
	_ "github.com/golang-migrate/migrate/v4/source/file"

	"database/sql"

	env "github.com/Netflix/go-env"

	_ "github.com/lib/pq"

	"log"
	"net/http"

	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"

	"github.com/streadway/amqp"
)

var (
	db    *sql.DB
	queue amqp.Queue
	ch    *amqp.Channel
)

type environment struct {
	PgsqlURI  string `env:"PGSQL_URI"`
	Listen    string `env:"LISTEN"`
	RabbitURI string `env:"RABBIT_URI"`
}

type jsonResponse struct {
	Success bool         `json:"success"`
	Message string       `json:"message"`
	Data    *interface{} `json:"data"`
}

func returnResponse(code int, msg string, data *interface{}, w http.ResponseWriter) {
	success := true
	if code >= 400 {
		success = false
	}
	respStruct := &jsonResponse{Success: success, Message: msg, Data: data}

	resp, _ := json.Marshal(respStruct)

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	w.Write(resp)
	w.Write([]byte("\n"))

	return
}

func main() {
	var err error

	// Getting configuration
	log.Printf("INFO: Getting environment variables\n")
	cnf := environment{}
	_, err = env.UnmarshalFromEnviron(&cnf)
	if err != nil {
		log.Fatal(err)
	}

	// Connecting to database
	log.Printf("INFO: Connecting to database")
	db, err = sql.Open("postgres", cnf.PgsqlURI)
	if err != nil {
		log.Fatalf("Can't connect to postgresql: %v", err)
	}

	// Running migrations
	driver, err := postgres.WithInstance(db, &postgres.Config{})
	if err != nil {
		log.Fatalf("Can't get postgres driver: %v", err)
	}
	m, err := migrate.NewWithDatabaseInstance("file://./migrations", "postgres", driver)
	if err != nil {
		log.Fatalf("Can't get migration object: %v", err)
	}
	m.Up()

	// Initialising rabbit mq
	// Initing rabbitmq
	conn, err := amqp.Dial(cnf.RabbitURI)
	if err != nil {
		log.Fatalf("Can't connect to rabbitmq")
	}
	defer conn.Close()

	ch, err = conn.Channel()
	if err != nil {
		log.Fatalf("Can't open channel")
	}
	defer ch.Close()

	err = initRabbit()
	if err != nil {
		log.Fatalf("Can't create rabbitmq queues: %s\n", err)
	}

	// Setting handlers for query
	log.Printf("INFO: Starting listening on %s\n", cnf.Listen)
	router := mux.NewRouter().StrictSlash(true)

	// PROJECTS
	router.HandleFunc("/requests", authMiddleware(getRequests)).Methods("GET")
	router.HandleFunc("/requests", authMiddleware(addRequest)).Methods("POST")
	router.HandleFunc("/requests/{name}", authMiddleware(getRequest)).Methods("GET")
	router.HandleFunc("/requests/{name}", authMiddleware(updRequest)).Methods("PUT")
	router.HandleFunc("/requests/{name}", authMiddleware(delRequest)).Methods("DELETE")

	http.ListenAndServe(cnf.Listen, handlers.LoggingHandler(os.Stdout, router))
}

func notImplemented(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Not Implemented\n"))
}

func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		tokenString := r.Header.Get("X-API-KEY")
		if tokenString != "804b95f13b714ee9912b19861faf3d25" {
			w.WriteHeader(http.StatusUnauthorized)
			w.Write([]byte("Missing Authorization Header\n"))
			return
		}

		next(w, r)
	})
}

func initRabbit() error {
	err := ch.ExchangeDeclare(
		"VideoParserExchange", // name
		"fanout",              // type
		true,                  // durable
		false,                 // auto delete
		false,                 // internal
		false,                 // no wait
		nil,                   // arguments
	)
	if err != nil {
		return err
	}

	err = ch.ExchangeDeclare(
		"VideoParserRetryExchange", // name
		"fanout",                   // type
		true,                       // durable
		false,                      // auto delete
		false,                      // internal
		false,                      // no wait
		nil,                        // arguments
	)
	if err != nil {
		return err
	}

	args := amqp.Table{"x-dead-letter-exchange": "VideoParserRetryExchange"}

	queue, err = ch.QueueDeclare(
		"VideoParserWorkerQueue", // name
		true,                     // durable - flush to disk
		false,                    // delete when unused
		false,                    // exclusive - only accessible by the connection that declares
		false,                    // no-wait - the queue will assume to be declared on the server
		args,                     // arguments -
	)
	if err != nil {
		return err
	}

	args = amqp.Table{"x-dead-letter-exchange": "VideoParserExchange", "x-message-ttl": 60000}
	queue, err = ch.QueueDeclare(
		"VideoParserWorkerRetryQueue", // name
		true,                          // durable - flush to disk
		false,                         // delete when unused
		false,                         // exclusive - only accessible by the connection that declares
		false,                         // no-wait - the queue will assume to be declared on the server
		args,                          // arguments -
	)
	if err != nil {
		return err
	}

	queue, err = ch.QueueDeclare(
		"VideoParserArchiveQueue", // name
		true,                      // durable - flush to disk
		false,                     // delete when unused
		false,                     // exclusive - only accessible by the connection that declares
		false,                     // no-wait - the queue will assume to be declared on the server
		nil,                       // arguments -
	)
	if err != nil {
		return err
	}

	err = ch.QueueBind("VideoParserWorkerQueue", "*", "VideoParserExchange", false, nil)
	if err != nil {
		return err
	}

	err = ch.QueueBind("VideoParserArchiveQueue", "*", "VideoParserExchange", false, nil)
	if err != nil {
		return err
	}

	err = ch.QueueBind("VideoParserWorkerRetryQueue", "*", "VideoParserRetryExchange", false, nil)
	if err != nil {
		return err
	}

	return nil
}