| 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_test |
| 15 |
|
| 16 |
import ( |
| 17 |
"log" |
| 18 |
"strconv" |
| 19 |
|
| 20 |
"github.com/nats-io/nats.go" |
| 21 |
"github.com/nats-io/nats.go/micro" |
| 22 |
) |
| 23 |
|
| 24 |
type rectangle struct { |
| 25 |
height int |
| 26 |
width int |
| 27 |
} |
| 28 |
|
| 29 |
// Handle is an implementation of micro.Handler used to |
| 30 |
// calculate the area of a rectangle |
| 31 |
func (r rectangle) Handle(req micro.Request) { |
| 32 |
area := r.height * r.width |
| 33 |
req.Respond([]byte(strconv.Itoa(area))) |
| 34 |
} |
| 35 |
|
| 36 |
func ExampleHandler() { |
| 37 |
nc, err := nats.Connect("127.0.0.1:4222") |
| 38 |
if err != nil { |
| 39 |
log.Fatal(err) |
| 40 |
} |
| 41 |
defer nc.Close() |
| 42 |
|
| 43 |
rec := rectangle{10, 5} |
| 44 |
|
| 45 |
config := micro.Config{ |
| 46 |
Name: "RectangleAreaService", |
| 47 |
Version: "0.1.0", |
| 48 |
Endpoint: µ.EndpointConfig{ |
| 49 |
Subject: "area.rectangle", |
| 50 |
Handler: rec, |
| 51 |
}, |
| 52 |
} |
| 53 |
svc, err := micro.AddService(nc, config) |
| 54 |
if err != nil { |
| 55 |
log.Fatal(err) |
| 56 |
} |
| 57 |
defer svc.Stop() |
| 58 |
} |