-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
74 lines (59 loc) · 1.53 KB
/
api.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
// go-rs/rest-api-framework
// Copyright(c) 2019-2022 Roshan Gade. All rights reserved.
// MIT Licensed
package rest
import (
"net/http"
)
type Handler func(Context)
type ErrorHandler func(error, Context)
type Router interface {
Use(Handler)
Router(string) Router
Get(string, Handler)
Post(string, Handler)
Put(string, Handler)
Delete(string, Handler)
CatchError(string, ErrorHandler)
}
type API interface {
Router
UncaughtException(ErrorHandler)
ServeHTTP(http.ResponseWriter, *http.Request)
}
type api struct {
prefix string
router *router
requestHandler *requestHandler
}
func (a *api) Router(prefix string) Router {
var router Router = &api{
prefix: trim(a.prefix + prefix),
router: a.router,
}
return router
}
func (a *api) Use(task Handler) {
a.router.middleware(a.prefix, task)
}
func (a *api) Get(pattern string, task Handler) {
a.router.route(http.MethodGet, a.prefix+pattern, task)
}
func (a *api) Post(pattern string, task Handler) {
a.router.route(http.MethodPost, a.prefix+pattern, task)
}
func (a *api) Put(pattern string, task Handler) {
a.router.route(http.MethodPut, a.prefix+pattern, task)
}
func (a *api) Delete(pattern string, task Handler) {
a.router.route(http.MethodDelete, a.prefix+pattern, task)
}
func (a *api) CatchError(code string, task ErrorHandler) {
a.router.exception(code, task)
}
func (a *api) UncaughtException(task ErrorHandler) {
a.router.unhandledException(task)
}
func (a *api) ServeHTTP(w http.ResponseWriter, r *http.Request) {
a.requestHandler.serveHTTP(w, r)
}