forked from webrpc/webrpc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
78 lines (63 loc) · 1.96 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
package main
import (
"context"
"log"
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/cors"
)
func main() {
err := startServer()
if err != nil {
log.Fatal(err)
}
}
func startServer() error {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
cors := cors.New(cors.Options{
// AllowedOrigins: []string{"https://foo.com"}, // Use this to allow specific origin hosts
AllowedOrigins: []string{"*"},
// AllowOriginFunc: func(r *http.Request, origin string) bool { return true },
AllowedMethods: []string{"POST", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300, // Maximum value not ignored by any of major browsers
})
r.Use(cors.Handler)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("."))
})
webrpcHandler := NewExampleServiceServer(&ExampleServiceRPC{})
r.Handle("/*", webrpcHandler)
return http.ListenAndServe(":4242", r)
}
type ExampleServiceRPC struct {
}
func (s *ExampleServiceRPC) Ping(ctx context.Context) (bool, error) {
return true, nil
}
func (s *ExampleServiceRPC) GetUser(ctx context.Context, userID uint64) (*User, error) {
if userID == 911 {
return nil, ErrorNotFound("unknown userID %d", 911)
// return nil, Errorf(ErrNotFound, "unknown userID %d", 911)
// return nil, WrapError(ErrNotFound, err, "unknown userID %d", 911)
}
return &User{
ID: userID,
Username: "hihi",
Meta: map[string]interface{}{"location": "Toronto"},
}, nil
}
func (s *ExampleServiceRPC) FindUsers(ctx context.Context, q string) (*Page, []*User, error) {
page := &Page{Num: 1}
users := []*User{
&User{ID: 1, Username: "a", Meta: map[string]interface{}{"location": "Montreal"}},
&User{ID: 2, Username: "b", Meta: map[string]interface{}{"age": 10}},
}
return page, users, nil
}