| 1 |
// Copyright 2022-2023 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package micro |
| 15 |
|
| 16 |
import ( |
| 17 |
"context" |
| 18 |
"encoding/json" |
| 19 |
"errors" |
| 20 |
"fmt" |
| 21 |
|
| 22 |
"github.com/nats-io/nats.go" |
| 23 |
) |
| 24 |
|
| 25 |
type ( |
| 26 |
// Handler is used to respond to service requests. |
| 27 |
Handler interface { |
| 28 |
Handle(Request) |
| 29 |
} |
| 30 |
|
| 31 |
// HandlerFunc is a function implementing [Handler]. |
| 32 |
// It allows using a function as a request handler, without having to implement Handle |
| 33 |
// on a separate type. |
| 34 |
HandlerFunc func(Request) |
| 35 |
|
| 36 |
// Request represents service request available in the service handler. |
| 37 |
// It exposes methods to respond to the request, as well as |
| 38 |
// getting the request data and headers. |
| 39 |
Request interface { |
| 40 |
// Respond sends the response for the request. |
| 41 |
// Additional headers can be passed using [WithHeaders] option. |
| 42 |
Respond([]byte, ...RespondOpt) error |
| 43 |
|
| 44 |
// RespondJSON marshals the given response value and responds to the request. |
| 45 |
// Additional headers can be passed using [WithHeaders] option. |
| 46 |
RespondJSON(any, ...RespondOpt) error |
| 47 |
|
| 48 |
// Error prepares and publishes error response from a handler. |
| 49 |
// A response error should be set containing an error code and description. |
| 50 |
// Optionally, data can be set as response payload. |
| 51 |
Error(code, description string, data []byte, opts ...RespondOpt) error |
| 52 |
|
| 53 |
// Data returns request data. |
| 54 |
Data() []byte |
| 55 |
|
| 56 |
// Headers returns request headers. |
| 57 |
Headers() Headers |
| 58 |
|
| 59 |
// Subject returns underlying NATS message subject. |
| 60 |
Subject() string |
| 61 |
|
| 62 |
// Reply returns underlying NATS message reply subject. |
| 63 |
Reply() string |
| 64 |
} |
| 65 |
|
| 66 |
// Headers is a wrapper around [*nats.Header] |
| 67 |
Headers nats.Header |
| 68 |
|
| 69 |
// RespondOpt is a function used to configure [Request.Respond] and [Request.RespondJSON] methods. |
| 70 |
RespondOpt func(*nats.Msg) |
| 71 |
|
| 72 |
// request is a default implementation of Request interface |
| 73 |
request struct { |
| 74 |
msg *nats.Msg |
| 75 |
respondError error |
| 76 |
} |
| 77 |
|
| 78 |
serviceError struct { |
| 79 |
Code string `json:"code"` |
| 80 |
Description string `json:"description"` |
| 81 |
} |
| 82 |
) |
| 83 |
|
| 84 |
var ( |
| 85 |
ErrRespond = errors.New("NATS error when sending response") |
| 86 |
ErrMarshalResponse = errors.New("marshaling response") |
| 87 |
ErrArgRequired = errors.New("argument required") |
| 88 |
) |
| 89 |
|
| 90 |
func (fn HandlerFunc) Handle(req Request) { |
| 91 |
fn(req) |
| 92 |
} |
| 93 |
|
| 94 |
// ContextHandler is a helper function used to utilize [context.Context] |
| 95 |
// in request handlers. |
| 96 |
func ContextHandler(ctx context.Context, handler func(context.Context, Request)) Handler { |
| 97 |
return HandlerFunc(func(req Request) { |
| 98 |
handler(ctx, req) |
| 99 |
}) |
| 100 |
} |
| 101 |
|
| 102 |
// Respond sends the response for the request. |
| 103 |
// Additional headers can be passed using [WithHeaders] option. |
| 104 |
func (r *request) Respond(response []byte, opts ...RespondOpt) error { |
| 105 |
respMsg := &nats.Msg{ |
| 106 |
Data: response, |
| 107 |
} |
| 108 |
for _, opt := range opts { |
| 109 |
opt(respMsg) |
| 110 |
} |
| 111 |
|
| 112 |
if err := r.msg.RespondMsg(respMsg); err != nil { |
| 113 |
r.respondError = fmt.Errorf("%w: %s", ErrRespond, err) |
| 114 |
return r.respondError |
| 115 |
} |
| 116 |
|
| 117 |
return nil |
| 118 |
} |
| 119 |
|
| 120 |
// RespondJSON marshals the given response value and responds to the request. |
| 121 |
// Additional headers can be passed using [WithHeaders] option. |
| 122 |
func (r *request) RespondJSON(response any, opts ...RespondOpt) error { |
| 123 |
resp, err := json.Marshal(response) |
| 124 |
if err != nil { |
| 125 |
return ErrMarshalResponse |
| 126 |
} |
| 127 |
return r.Respond(resp, opts...) |
| 128 |
} |
| 129 |
|
| 130 |
// Error prepares and publishes error response from a handler. |
| 131 |
// A response error should be set containing an error code and description. |
| 132 |
// Optionally, data can be set as response payload. |
| 133 |
func (r *request) Error(code, description string, data []byte, opts ...RespondOpt) error { |
| 134 |
if code == "" { |
| 135 |
return fmt.Errorf("%w: error code", ErrArgRequired) |
| 136 |
} |
| 137 |
if description == "" { |
| 138 |
return fmt.Errorf("%w: description", ErrArgRequired) |
| 139 |
} |
| 140 |
response := &nats.Msg{ |
| 141 |
Header: nats.Header{ |
| 142 |
ErrorHeader: []string{description}, |
| 143 |
ErrorCodeHeader: []string{code}, |
| 144 |
}, |
| 145 |
} |
| 146 |
for _, opt := range opts { |
| 147 |
opt(response) |
| 148 |
} |
| 149 |
|
| 150 |
response.Data = data |
| 151 |
if err := r.msg.RespondMsg(response); err != nil { |
| 152 |
r.respondError = err |
| 153 |
return err |
| 154 |
} |
| 155 |
r.respondError = &serviceError{ |
| 156 |
Code: code, |
| 157 |
Description: description, |
| 158 |
} |
| 159 |
|
| 160 |
return nil |
| 161 |
} |
| 162 |
|
| 163 |
// WithHeaders can be used to configure response with custom headers. |
| 164 |
func WithHeaders(headers Headers) RespondOpt { |
| 165 |
return func(m *nats.Msg) { |
| 166 |
if m.Header == nil { |
| 167 |
m.Header = nats.Header(headers) |
| 168 |
return |
| 169 |
} |
| 170 |
|
| 171 |
for k, v := range headers { |
| 172 |
m.Header[k] = v |
| 173 |
} |
| 174 |
} |
| 175 |
} |
| 176 |
|
| 177 |
// Data returns request data. |
| 178 |
func (r *request) Data() []byte { |
| 179 |
return r.msg.Data |
| 180 |
} |
| 181 |
|
| 182 |
// Headers returns request headers. |
| 183 |
func (r *request) Headers() Headers { |
| 184 |
return Headers(r.msg.Header) |
| 185 |
} |
| 186 |
|
| 187 |
// Subject returns underlying NATS message subject. |
| 188 |
func (r *request) Subject() string { |
| 189 |
return r.msg.Subject |
| 190 |
} |
| 191 |
|
| 192 |
// Reply returns underlying NATS message reply subject. |
| 193 |
func (r *request) Reply() string { |
| 194 |
return r.msg.Reply |
| 195 |
} |
| 196 |
|
| 197 |
// Get gets the first value associated with the given key. |
| 198 |
// It is case-sensitive. |
| 199 |
func (h Headers) Get(key string) string { |
| 200 |
return nats.Header(h).Get(key) |
| 201 |
} |
| 202 |
|
| 203 |
// Values returns all values associated with the given key. |
| 204 |
// It is case-sensitive. |
| 205 |
func (h Headers) Values(key string) []string { |
| 206 |
return nats.Header(h).Values(key) |
| 207 |
} |
| 208 |
|
| 209 |
func (e *serviceError) Error() string { |
| 210 |
return fmt.Sprintf("%s:%s", e.Code, e.Description) |
| 211 |
} |