-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
74 lines (59 loc) · 1.61 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
package main
import (
"fmt"
"log"
"net/http"
"github.com/codegangsta/negroni"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
"github.com/jmoiron/sqlx"
"github.com/gkiryaziev/go-gorilla-sqlx/conf"
"github.com/gkiryaziev/go-gorilla-sqlx/handlers/users"
)
// checkError check errors
func checkError(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
// load config
config, err := conf.NewConfig("config.yaml").Load()
checkError(err)
// mysql connection string
mysqlBind := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True",
config.DB.UserName,
config.DB.UserPassword,
config.DB.Host,
config.DB.Port,
config.DB.Database,
)
// http server address and port
hostBind := fmt.Sprintf("%s:%s",
config.Host.IP,
config.Host.Port,
)
// open connection to database
db, err := sqlx.Connect("mysql", mysqlBind)
checkError(err)
db.SetMaxIdleConns(100)
defer db.Close()
// handlers
userHandler := users.NewUserHandler(db)
mx := mux.NewRouter()
// user handler
mx.HandleFunc("/api/v1/users", userHandler.GetUsers).Methods("GET")
mx.HandleFunc("/api/v1/users/{id}", userHandler.GetUser).Methods("GET")
mx.HandleFunc("/api/v1/users", userHandler.UpdateUser).Methods("PUT")
mx.HandleFunc("/api/v1/users/{id}", userHandler.DeleteUser).Methods("DELETE")
mx.HandleFunc("/api/v1/users", userHandler.InsertUser).Methods("POST")
// static
mx.PathPrefix("/").Handler(http.FileServer(http.Dir("public")))
// negroni
ng := negroni.New()
ng.UseHandler(mx)
// start server
log.Println("Listening on", hostBind)
err = http.ListenAndServe(hostBind, ng)
checkError(err)
}