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

     1  package main
     2  
     3  import (
     4  	"log"
     5  
     6  	proto "github.com/micro/go-micro/examples/api/rpc/proto"
     7  	"github.com/micro/go-micro/v2"
     8  	"github.com/micro/go-micro/v2/api"
     9  	rapi "github.com/micro/go-micro/v2/api/handler/api"
    10  	"github.com/micro/go-micro/v2/api/handler/rpc"
    11  	"github.com/micro/go-micro/v2/errors"
    12  
    13  	"context"
    14  )
    15  
    16  type Example struct{}
    17  
    18  type Foo struct{}
    19  
    20  // Example.Call is a method which will be served by http request /example/call
    21  // In the event we see /[service]/[method] the [service] is used as part of the method
    22  // E.g /example/call goes to go.micro.api.example Example.Call
    23  func (e *Example) Call(ctx context.Context, req *proto.CallRequest, rsp *proto.CallResponse) error {
    24  	log.Print("Received Example.Call request")
    25  
    26  	if len(req.Name) == 0 {
    27  		return errors.BadRequest("go.micro.api.example", "no content")
    28  	}
    29  
    30  	rsp.Message = "got your request " + req.Name
    31  	return nil
    32  }
    33  
    34  // Foo.Bar is a method which will be served by http request /example/foo/bar
    35  // Because Foo is not the same as the service name it is mapped beyond /example/
    36  func (f *Foo) Bar(ctx context.Context, req *proto.EmptyRequest, rsp *proto.EmptyResponse) error {
    37  	log.Print("Received Foo.Bar request")
    38  
    39  	// noop
    40  
    41  	return nil
    42  }
    43  
    44  func main() {
    45  	service := micro.NewService(
    46  		micro.Name("go.micro.api.example"),
    47  	)
    48  
    49  	service.Init()
    50  
    51  	// register example handler
    52  	proto.RegisterExampleHandler(service.Server(), new(Example), api.WithEndpoint(&api.Endpoint{
    53  		// The RPC method
    54  		Name: "Example.Call",
    55  		// The HTTP paths. This can be a POSIX regex
    56  		Path: []string{"/example"},
    57  		// The HTTP Methods for this endpoint
    58  		Method: []string{"POST"},
    59  		// The API handler to use
    60  		Handler: rpc.Handler,
    61  	}))
    62  
    63  	// register foo handler
    64  	proto.RegisterFooHandler(service.Server(), new(Foo), api.WithEndpoint(&api.Endpoint{
    65  		// The RPC method
    66  		Name: "Foo.Bar",
    67  		// The HTTP paths. This can be a POSIX regex
    68  		Path: []string{"/foo/bar"},
    69  		// The HTTP Methods for this endpoint
    70  		Method: []string{"POST"},
    71  		// The API handler to use
    72  		Handler: rapi.Handler,
    73  	}))
    74  
    75  	if err := service.Run(); err != nil {
    76  		log.Fatal(err)
    77  	}
    78  }