forked from ryankurte/go-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.go
More file actions
90 lines (69 loc) · 1.96 KB
/
example.go
File metadata and controls
90 lines (69 loc) · 1.96 KB
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
package main
import (
"os"
log "github.com/sirupsen/logrus"
"github.com/ryankurte/go-api/lib"
"github.com/ryankurte/go-api/lib/options"
)
// AppConfig Application configuration object
type AppConfig struct {
options.Base
}
// AppContext Application Context object
// Route handlers are called against this
type AppContext struct {
Mock string
}
// Request Input structure for parsing
type Request struct {
Message string `valid:"ascii,required"`
Option string `valid:"ascii,optional"`
}
// Response Output structure for parsing
type Response struct {
Message string `valid:"ascii,required"`
}
// FakeEndpoint AppContext Endpoint handler function
func (c *AppContext) FakeEndpoint(i Request) (Response, error) {
o := Response{i.Message}
log.Printf("APP Endpoint context: %+v in: %+v out: %+v\n", c, i, o)
return o, nil
}
// APIContext sub context
type APIContext struct {
*AppContext
}
// FakeEndpoint APIContext Endpoint handler function
func (c *APIContext) FakeEndpoint(i Request) (Response, error) {
o := Response{i.Message}
log.Printf("API Endpoint context: %+v in: %+v out: %+v\n", c, i, o)
return o, nil
}
func main() {
// Load application config
o := AppConfig{}
err := options.Parse(&o)
if err != nil {
os.Exit(0)
}
// Create API instance with base context
ctx := AppContext{"Whoop whoop"}
api, err := api.New(ctx, &o.Base)
if err != nil {
log.Print(err)
os.Exit(-2)
}
// Register logging plugin
//api.RegisterPlugin(plugins.NewLogPlugin())
// Register static middleware
//api.Middleware(web.StaticMiddleware("./static", web.StaticOption{IndexFile: "index.html"}))
// Attach base endpoint
api.RegisterEndpoint("/", "POST", (*AppContext).FakeEndpoint)
api.RegisterEndpoint("/", "GET", (*AppContext).FakeEndpoint)
// Create subrouter with sub context and register endpoint
apiCtx := APIContext{}
sr := api.Subrouter(apiCtx, "/api")
sr.RegisterEndpoint("/test", "POST", (*APIContext).FakeEndpoint)
// Start API server
api.Run()
}