This repository has been archived by the owner on Sep 9, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
148 lines (122 loc) · 3.82 KB
/
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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
package king
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/altipla-consulting/king/peer"
"github.com/altipla-consulting/king/runtime"
"github.com/altipla-consulting/sentry"
"github.com/juju/errors"
"github.com/julienschmidt/httprouter"
"go.opencensus.io/exporter/stackdriver/propagation"
"go.opencensus.io/trace"
"github.com/altipla-consulting/king/internal/httperr"
)
type Server struct {
router *httprouter.Router
errorMiddlewares []ErrorMiddleware
debug bool
traceOptions []trace.StartOption
}
type ErrorMiddleware func(ctx context.Context, appErr error)
type ServerOption func(server *Server)
func NewServer(opts ...ServerOption) *Server {
server := new(Server)
for _, opt := range opts {
opt(server)
}
server.traceOptions = append(server.traceOptions, trace.WithSpanKind(trace.SpanKindServer))
if server.router != nil {
for _, svc := range runtime.Services {
for _, method := range svc.Methods {
path := fmt.Sprintf("/_/%s/%s", svc.Name, method.Name)
server.router.POST(path, buildHandler(fmt.Sprintf("%s.%s", svc.Name, method.Name), server, method))
}
}
}
return server
}
func buildHandler(name string, server *Server, method *runtime.Method) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
f := new(propagation.HTTPFormat)
sc, ok := f.SpanContextFromRequest(r)
if ok {
ctx, span := trace.StartSpanWithRemoteParent(r.Context(), name, sc, server.traceOptions...)
defer span.End()
r = r.WithContext(ctx)
}
inCodec := runtime.CodecFromType(r.Header.Get("Content-Type"))
outCodec := runtime.CodecFromType(r.Header.Get("Accept"))
w.Header().Set("Content-Type", outCodec.ContentType())
r = r.WithContext(sentry.WithContext(r.Context()))
header := r.Header.Get("X-King-Deadline")
if header != "" {
var deadline time.Time
if err := deadline.UnmarshalText([]byte(header)); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
for _, m := range server.errorMiddlewares {
m(r.Context(), err)
}
return
}
ctx, cancel := context.WithDeadline(r.Context(), deadline)
defer cancel()
r = r.WithContext(ctx)
}
// Este WithContext debe mantenerse siempre el último dado que debe guardar una petición
// con todos los valores ya introducidos.
r = r.WithContext(peer.RequestWithContext(r))
in := method.Input()
if err := inCodec.Decode(r.Body, in); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
for _, m := range server.errorMiddlewares {
m(r.Context(), err)
}
return
}
out, err := method.Handler(r.Context(), in)
if err != nil {
for _, m := range server.errorMiddlewares {
m(r.Context(), err)
}
kingErr := &runtime.KingError{
Message: err.Error(),
}
switch {
case errors.IsNotFound(err):
kingErr.Err = httperr.ErrorTypeNotFound
case errors.IsUnauthorized(err):
kingErr.Err = httperr.ErrorTypeUnauthorized
case errors.IsNotImplemented(err):
kingErr.Err = httperr.ErrorTypeNotImplemented
case errors.IsNotValid(err):
kingErr.Err = httperr.ErrorTypeNotValid
case errors.IsForbidden(err):
kingErr.Err = httperr.ErrorTypeForbidden
default:
kingErr.Err = httperr.ErrorTypeInternalServerError
}
data, err := json.Marshal(kingErr)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
for _, m := range server.errorMiddlewares {
m(r.Context(), err)
}
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
http.Error(w, string(data), httperr.KingErrStatus[kingErr.Err])
return
}
if err := outCodec.Encode(w, out); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
for _, m := range server.errorMiddlewares {
m(r.Context(), err)
}
return
}
return
}
}