-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.go
57 lines (47 loc) · 1.5 KB
/
app.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
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
_ "github.com/denisenkom/go-mssqldb"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
)
type App struct {
Router *mux.Router
DB *sql.DB
}
func (a *App) Initialize(db_type, db_user, db_password, db_host, db_database, db_params string) {
var connStr string
switch db_type {
case "sqlserver":
connStr = fmt.Sprintf("%s://%s:%s@%s/instance?database=%s&%s", db_type, db_user, db_password, db_host, db_database, db_params)
default:
connStr = fmt.Sprintf("%s://%s:%s@%s/%s?%s", db_type, db_user, db_password, db_host, db_database, db_params)
}
fmt.Print(connStr)
var err error
a.DB, err = sql.Open(db_type, connStr)
if err != nil {
log.Fatal(err)
}
a.Router = mux.NewRouter()
a.initializeRoutes()
}
func (a *App) Run(addr string) {
fmt.Printf("Server running on %s \n", addr)
credentials := handlers.AllowCredentials()
methods := handlers.AllowedMethods([]string{"GET", "POST"})
// ttl := handlers.MaxAge(3600)
origins := handlers.AllowedOrigins([]string{"*"})
log.Fatal(http.ListenAndServe(addr, handlers.CORS(credentials, methods, origins)(a.Router)))
}
func (a *App) initializeRoutes() {
api := a.Router.PathPrefix("/api/v1").Subrouter()
api.HandleFunc("/", a.getRequest).Methods(http.MethodGet)
api.HandleFunc("/make-db-request", a.apiMakeDbRequest).Methods(http.MethodPost)
api.HandleFunc("/", a.notFound)
api.HandleFunc("/user/{userID}/comment/{commentID}", a.withParams).Methods(http.MethodGet)
}