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

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"log"
     6  
     7  	"github.com/emicklei/go-restful"
     8  
     9  	hello "github.com/micro/go-micro/examples/greeter/srv/proto/hello"
    10  	"github.com/micro/go-micro/v2/client"
    11  	"github.com/micro/go-micro/v2/web"
    12  )
    13  
    14  type Say struct{}
    15  
    16  var (
    17  	cl hello.SayService
    18  )
    19  
    20  func (s *Say) Anything(req *restful.Request, rsp *restful.Response) {
    21  	log.Print("Received Say.Anything API request")
    22  	rsp.WriteEntity(map[string]string{
    23  		"message": "Hi, this is the Greeter API",
    24  	})
    25  }
    26  
    27  func (s *Say) Hello(req *restful.Request, rsp *restful.Response) {
    28  	log.Print("Received Say.Hello API request")
    29  
    30  	name := req.PathParameter("name")
    31  
    32  	response, err := cl.Hello(context.TODO(), &hello.Request{
    33  		Name: name,
    34  	})
    35  
    36  	if err != nil {
    37  		rsp.WriteError(500, err)
    38  	}
    39  
    40  	rsp.WriteEntity(response)
    41  }
    42  
    43  func main() {
    44  	// Create service
    45  	service := web.NewService(
    46  		web.Name("go.micro.api.greeter"),
    47  	)
    48  
    49  	service.Init()
    50  
    51  	// setup Greeter Server Client
    52  	cl = hello.NewSayService("go.micro.srv.greeter", client.DefaultClient)
    53  
    54  	// Create RESTful handler
    55  	say := new(Say)
    56  	ws := new(restful.WebService)
    57  	wc := restful.NewContainer()
    58  	ws.Consumes(restful.MIME_XML, restful.MIME_JSON)
    59  	ws.Produces(restful.MIME_JSON, restful.MIME_XML)
    60  	ws.Path("/greeter")
    61  	ws.Route(ws.GET("/").To(say.Anything))
    62  	ws.Route(ws.GET("/{name}").To(say.Hello))
    63  	wc.Add(ws)
    64  
    65  	// Register Handler
    66  	service.Handle("/", wc)
    67  
    68  	// Run server
    69  	if err := service.Run(); err != nil {
    70  		log.Fatal(err)
    71  	}
    72  }