-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
91 lines (73 loc) · 1.94 KB
/
server.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
80
81
82
83
84
85
86
87
88
89
90
91
package web
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/aewens/anda-server/internal/storage"
"github.com/aewens/anda-server/pkg/core"
)
type handler func(http.ResponseWriter, *http.Request)
type routeMap map[string]handler
type routeMethodMap map[string]routeMap
type Server struct {
Config *core.Config
DB *sql.DB
Router *mux.Router
Routes routeMethodMap
}
type Response struct {
Error bool `json:"err"`
Name string `json:"name"`
Data interface{} `json:"data"`
}
type callback func(*Server) *Response
func jsonMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
next.ServeHTTP(w, r)
})
}
func routeWrapper(res *Response) handler {
return func(w http.ResponseWriter, r *http.Request) {
err := json.NewEncoder(w).Encode(&res)
if err != nil {
log.Println(err)
fmt.Fprint(w, err.Error())
}
}
}
func (server *Server) AddRoute(method string, route string, callback callback) {
handle := routeWrapper(callback(server))
server.Routes[method][route] = handle
server.Router.HandleFunc(route, handle).Methods(method)
}
func Create(config *core.Config) (*Server, error) {
db, err := storage.OpenPostgreSQL(config)
if err != nil {
return nil, err
}
router := mux.NewRouter().StrictSlash(true)
router.Use(jsonMiddleware)
routes := make(routeMethodMap)
routes["GET"] = make(routeMap)
routes["POST"] = make(routeMap)
routes["PUT"] = make(routeMap)
routes["DELETE"] = make(routeMap)
server := &Server{
Config: config,
DB: db,
Router: router,
Routes: routes,
}
return server, nil
}
func (server *Server) Start() {
defer server.DB.Close()
// Start HTTP server
httpPort := fmt.Sprintf(":%d", server.Config.ApiPort)
fmt.Printf("Starting server on port %s\n", httpPort)
log.Println(http.ListenAndServe(httpPort, server.Router))
}