-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmain.go
63 lines (51 loc) · 1.51 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
package main
import (
"books-list/controllers"
"books-list/driver"
"books-list/models"
"database/sql"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/subosito/gotenv"
)
var books []models.Book
var db *sql.DB
func init() {
gotenv.Load()
}
func logFatal(err error) {
if err != nil {
log.Fatal(err)
}
}
type WithCORS struct {
r *mux.Router
}
// Simple wrapper to Allow CORS.
// See: http://stackoverflow.com/a/24818638/1058612.
func (s *WithCORS) ServeHTTP(res http.ResponseWriter, req *http.Request) {
if origin := req.Header.Get("Origin"); origin != "" {
res.Header().Set("Access-Control-Allow-Origin", origin)
res.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
res.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
// Stop here for a Preflighted OPTIONS request.
if req.Method == "OPTIONS" {
return
}
// Lets Gorilla work
s.r.ServeHTTP(res, req)
}
func main() {
db = driver.ConnectDB()
router := mux.NewRouter()
controller := controllers.Controller{}
router.HandleFunc("/books", controller.GetBooks(db)).Methods("GET")
router.HandleFunc("/books/{id}", controller.GetBook(db)).Methods("GET")
router.HandleFunc("/books", controller.AddBook(db)).Methods("POST")
router.HandleFunc("/books", controller.UpdateBook(db)).Methods("PUT")
router.HandleFunc("/books/{id}", controller.RemoveBook(db)).Methods("DELETE")
log.Fatal(http.ListenAndServe(":8000", &WithCORS{router}))
}