-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.go
94 lines (79 loc) · 2.38 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"bytes"
"encoding/json"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/go-chi/oauth"
)
/*
Resource Server Example
Get Customers
GET http://localhost:3200/customers
User-Agent: Fiddler
Host: localhost:3200
Content-Length: 0
Content-Type: application/json
Authorization: Bearer {access_token}
Get Orders
GET http://localhost:3200/customers/12345/orders
User-Agent: Fiddler
Host: localhost:3200
Content-Length: 0
Content-Type: application/json
Authorization: Bearer {access_token}
{access_token} is produced by the Authorization Server response (see example /test/authserver).
*/
func main() {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "PUT", "POST", "DELETE", "HEAD", "OPTION"},
AllowedHeaders: []string{"User-Agent", "Content-Type", "Accept", "Accept-Encoding", "Accept-Language", "Cache-Control", "Connection", "DNT", "Host", "Origin", "Pragma", "Referer"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300, // Maximum value not ignored by any of major browsers
}))
registerAPI(r)
_ = http.ListenAndServe(":8081", r)
}
func registerAPI(r *chi.Mux) {
r.Route("/", func(r chi.Router) {
// use the Bearer Authentication middleware
r.Use(oauth.Authorize("mySecretKey-10101", nil))
r.Get("/customers", GetCustomers)
r.Get("/customers/{id}/orders", GetOrders)
})
}
func renderJSON(w http.ResponseWriter, v interface{}, statusCode int) {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(true)
if err := enc.Encode(v); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(statusCode)
_, _ = w.Write(buf.Bytes())
}
func GetCustomers(w http.ResponseWriter, _ *http.Request) {
renderJSON(w, `{
"Status": "verified",
"Customer": "test001",
"Customer_name": "Max",
"Customer_email": "[email protected]",
}`, http.StatusOK)
}
func GetOrders(w http.ResponseWriter, _ *http.Request) {
renderJSON(w, `{
"status": "sent",
"customer": "test001",
"order_id": "100234",
"total_order_items": "199",
}`, http.StatusOK)
}