-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
37 lines (29 loc) · 878 Bytes
/
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
package main
import (
"net/http"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
type ApiServer struct {
listenAddr string
router *mux.Router
}
func NewApiServer(port string) *ApiServer {
return &ApiServer{
listenAddr: port,
router: mux.NewRouter(),
}
}
func (s *ApiServer) Run() error {
return http.ListenAndServe(s.listenAddr, handlers.CORS(
handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}),
handlers.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}),
handlers.AllowedOrigins([]string{"*"}),
)(s.router))
}
func (s *ApiServer) RegisterHandlerFunc(path string, f func(w http.ResponseWriter, r *http.Request), methods ...string) {
s.router.HandleFunc(path, f).Methods(methods...)
}
func (s *ApiServer) UseMiddleware(f func(http.Handler) http.Handler) {
s.router.Use(f)
}