github.com/micro/go-micro/examples@v0.0.0-20210105173217-bf4ab679e18b/template/api/handler/example.go (about) 1 package handler 2 3 import ( 4 "context" 5 "encoding/json" 6 "github.com/micro/go-micro/v2/util/log" 7 8 "github.com/micro/go-micro/examples/template/api/client" 9 example "github.com/micro/go-micro/examples/template/srv/proto/example" 10 api "github.com/micro/go-micro/v2/api/proto" 11 "github.com/micro/go-micro/v2/errors" 12 ) 13 14 type Example struct{} 15 16 func extractValue(pair *api.Pair) string { 17 if pair == nil { 18 return "" 19 } 20 if len(pair.Values) == 0 { 21 return "" 22 } 23 return pair.Values[0] 24 } 25 26 // Example.Call is called by the API as /template/example/call with post body {"name": "foo"} 27 func (e *Example) Call(ctx context.Context, req *api.Request, rsp *api.Response) error { 28 log.Log("Received Example.Call request") 29 30 // extract the client from the context 31 exampleClient, ok := client.ExampleFromContext(ctx) 32 if !ok { 33 return errors.InternalServerError("go.micro.api.template.example.call", "example client not found") 34 } 35 36 // make request 37 response, err := exampleClient.Call(ctx, &example.Request{ 38 Name: extractValue(req.Post["name"]), 39 }) 40 if err != nil { 41 return errors.InternalServerError("go.micro.api.template.example.call", err.Error()) 42 } 43 44 b, _ := json.Marshal(response) 45 46 rsp.StatusCode = 200 47 rsp.Body = string(b) 48 49 return nil 50 }