github.com/micro/go-micro/examples@v0.0.0-20210105173217-bf4ab679e18b/greeter/api/api.go (about)

     1  package main
     2  
     3  import (
     4  	"encoding/json"
     5  	"log"
     6  	"strings"
     7  
     8  	hello "github.com/micro/go-micro/examples/greeter/srv/proto/hello"
     9  	"github.com/micro/go-micro/v2"
    10  	api "github.com/micro/go-micro/v2/api/proto"
    11  	"github.com/micro/go-micro/v2/errors"
    12  
    13  	"context"
    14  )
    15  
    16  type Say struct {
    17  	Client hello.SayService
    18  }
    19  
    20  func (s *Say) Hello(ctx context.Context, req *api.Request, rsp *api.Response) error {
    21  	log.Print("Received Say.Hello API request")
    22  
    23  	name, ok := req.Get["name"]
    24  	if !ok || len(name.Values) == 0 {
    25  		return errors.BadRequest("go.micro.api.greeter", "Name cannot be blank")
    26  	}
    27  
    28  	response, err := s.Client.Hello(ctx, &hello.Request{
    29  		Name: strings.Join(name.Values, " "),
    30  	})
    31  	if err != nil {
    32  		return err
    33  	}
    34  
    35  	rsp.StatusCode = 200
    36  	b, _ := json.Marshal(map[string]string{
    37  		"message": response.Msg,
    38  	})
    39  	rsp.Body = string(b)
    40  
    41  	return nil
    42  }
    43  
    44  func main() {
    45  	service := micro.NewService(
    46  		micro.Name("go.micro.api.greeter"),
    47  	)
    48  
    49  	// parse command line flags
    50  	service.Init()
    51  
    52  	service.Server().Handle(
    53  		service.Server().NewHandler(
    54  			&Say{Client: hello.NewSayService("go.micro.srv.greeter", service.Client())},
    55  		),
    56  	)
    57  
    58  	if err := service.Run(); err != nil {
    59  		log.Fatal(err)
    60  	}
    61  }