当前位置:网站首页>Go microservice restful API design standards and practices

Go microservice restful API design standards and practices

2022-06-11 12:41:00 Dawnlighttt

RESTful API Design standards and practices



background

In the previous sessions , It has been introduced that go-micro Some core functions and core mechanisms of . The implementation is focused on micro services . In the actual development process , Microservices need to be deployed only as background programs , Need overall direction web Front end client products provide interaction and data . therefore , Let's take a look at how microservices work with web Interact .

Divide the call scope

In the overall system architecture , We will divide the system into foreground and background . The front desk is responsible for interacting with users , Display data , Perform the operation . The background is responsible for business logic processing , Data persistence and other operations . During the operation of the system , Front and back , Function calls can occur in both the background and the background :

  • Internal calls : Mutual calls between various micro services in the background , It belongs to the internal call of the system background , Call it an internal call .

  • External call : The interface between the foreground and the background requests to call , It is often called an external call .

Technology selection

In development practice , Our technical solutions for external calls and internal calls will be different .

  • RPC call : Internal calls between various services in the background , In order to achieve efficient service interaction , Usually used RPC The way to achieve .

  • REST: For front-end clients, you can use HTTP Interface , Scenes interacting with the background . Because it involves the management and operation of different resources , So... Is often used RESTful Standards .

Go-Micro API gateway

Micro There is... In the frame API Function of gateway .API The role of the gateway is to act as a proxy for microservices , Be responsible for the RPC Method proxy support HTTP Agreed web request , At the same time, the URL Exposure .

install Micro Tools

Want to use go-micro Of api Gateway function . Need to download Micro Source code and install Mico.

install Micro

You can go directly through go get Command download and install , The specific command is :

go get -u github.com/micro/micro

In the use of go get Command to download the source code and corresponding dependencies , Due to the problems of network environment in China , Errors that may cause the download to fail .

If a connection timeout error occurs during the installation process , You can download the corresponding dependent libraries manually , Then install it manually . therefore , The solution is divided into two steps :

install golang Of net、crypt、text Such as the library
git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/grpc  
git clone https://github.com/golang/net.git $GOPATH/src/golang.org/x/net  
git clone https://github.com/golang/text.git $GOPATH/src/golang.org/x/text  
git clone https://github.com/golang/crypto.git $GOPATH/src/golang.org/x/crypto

Use git clone Command to download the required code base .

install micro
go install github.com/micro/micro

Use go install Command to install micro frame , Wait for the command execution to finish .

test Micro Installation successful

micro After the series of tools are successfully installed , Can be checked by command .

micro --version
micro version 1.9.1

Above , Output micro version 1.9.1 It indicates that the micro Installation successful .

Micro API working principle

micro Tools provide the ability to build api Functions of gateway service , And based on go-micro Framework for programming , The core function is to RPC Forms of service proxies become supported HTTP Agreed WEB API request .

function Micro api service

You can start... With the following command micro api:

micro api

Reverse proxy API Service startup

stay Micro api In function , Support a variety of ways to handle request routing , We call it Handler. Include :API Handler、RPC Handler、 Reverse proxy 、Event Handler,RPC Etc . In this case , We use a reverse proxy to demonstrate .

Reverse proxy

  • Format :/[service]
  • request / Respond to :HTTP The way
  • micro api Startup pass –handler=proxy Set up

therefore , In the form of a reverse proxy micro api The gateway service startup command is :

micro api --handler=http

In this case , We will micro api Reverse proxy and REST Representative HTTP WEB Requests are used together .

install go-restful

You can install go-restful Library to implement RESTful Style path mapping , So as to achieve HTTP Of WEB API service . install go-restful The command is as follows :

go get github.com/emicklei/go-restful

Let's use a service to get information about a student as an example , Explain micro api Programming implementation of .

Service definition and compilation

Define the student message body proto file :

syntax = 'proto3';
package proto;
option go_package="./;proto";
message Student {
    string id = 1;
    string name = 2;
    int32 grade = 3;
    string classes = 4;
}
message Request {
    string name = 1;
}
service StudentService {
    rpc GetStudent (Request) returns (Student);
}

stay proto It's defined in the file Student、Request Message body and rpc service . Use micro api Gateway function , compile proto file , Need generation micro file . To compile and generate this file, you need to use a new protoc-gen-micro library , install protoc-gen-micro The library commands are as follows :

go get github.com/micro/protoc-gen-micro

Compile again proto file , You need to specify two parameters , Namely :go_out and micro_out, The detailed order is as follows :

protoc --go_out=. --micro_out=. student.proto

After the above command is executed successfully , Will automatically generate two go Language file :student.pb.go and student.micro.go.

micro.go The generated content in the file contains the instantiation of the service , And the underlying implementation of the corresponding service methods .

Server implementation

We all know that normal Web service , It is processed through routing http Requested by . The same is true here , We can resolve by routing HTTP Requested interface ,service Object contains the route handling method . The detailed code is as follows :

...
type StudentServiceImpl struct {
    
}
// Service implementation 
func (ss *StudentServiceImpl) GetStudent(ctx context.Context, request *proto.Request, resp *proto.Student) error {
    
	//tom
	studentMap := map[string]proto.Student{
    
		"davie":  proto.Student{
    Name: "davie", Classes: " Software engineering ", Grade: 80},
		"steven": proto.Student{
    Name: "steven", Classes: " Computer science and technology ", Grade: 90},
		"tony":   proto.Student{
    Name: "tony", Classes: " Computer network engineering ", Grade: 85},
		"jack":   proto.Student{
    Name: "jack", Classes: " business administration ", Grade: 96},
	}
	if request.Name == "" {
    
		return errors.New("  Request parameter error , Please request again .")
	}
	// Get the corresponding student
	student := studentMap[request.Name]
	if student.Name != "" {
    
		fmt.Println(student.Name, student.Classes, student.Grade)
		*resp = student
		return nil
	}
	return errors.New("  Relevant student information is not queried  ")
}
func main() {
    
	service := micro.NewService(
		micro.Name("go.micro.srv.student"),
	)
	service.Init()
    proto.RegisterStudentServiceHandler(service.Server(), new(StudentServiceImpl))
	if err := service.Run(); err != nil {
    
		log.Fatal(err.Error())
	}
}
...

server The program implements the service and runs the service .

REST mapping

Now? ,RPC The service has been written . We need to program it API Agent function of , Used for processing HTTP Formal request .
stay rest.go In file , Realization rest Mapping , The detailed code is as follows :

type Student struct {
    
}
var (
	cli proto.StudentService
)
// http Request handling function 
func (s *Student) GetStudent(req *restful.Request, rsp *restful.Response) {
    
	name := req.PathParameter("name")
	fmt.Println(name)
	//  Core code 
	//  Use cli call RPC function , So as to achieve RPC Forms of service proxies become supported HTTP Agreed WEB API request .
	response, err := cli.GetStudent(context.TODO(), &proto.Request{
    
		Name: name,
	})
	if err != nil {
    
		fmt.Println(err.Error())
		rsp.WriteError(500, err)
	}
	rsp.WriteEntity(response)
}
func main() {
    
	//  Notice that here you create a web service 
	service := web.NewService(
		web.Name("go.micro.api.student"),
	)
	service.Init()
	//  Instantiation cli object 
	cli = proto.NewStudentService("go.micro.srv.student", client.DefaultClient)
	student := new(Student)
	ws := new(restful.WebService)
	ws.Path("/student")
	ws.Consumes(restful.MIME_XML, restful.MIME_JSON)
	ws.Produces(restful.MIME_JSON, restful.MIME_XML)
	ws.Route(ws.GET("/{name}").To(student.GetStudent))
	wc := restful.NewContainer()
	wc.Add(ws)
	service.Handle("/", wc)
	if err := service.Run(); err != nil {
    
		log.Fatal(err)
	}
}
原网站

版权声明
本文为[Dawnlighttt]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203012126422532.html