Go golang Micro Services Framework go-micro Getting Started Notes 2.1 micro Tool micro api

Keywords: Front-end curl JSON IE github

micro api

The microfunction is very powerful, and this article will elaborate on the capabilities of the micro api command line Say important things three times

Main role

The primary purpose is to provide http gateway support for microservices.If the back-end service name is go.micro.srv.hello and the call method is provided, we can invoke the micro service through the http protocol.

curl http://127.0.0.0:8080/hello/call?name=123

The micro api directive has all the following parameters

$micro api -h
NAME:
   micro api - Run the api gateway

USAGE:
   micro api [command options] [arguments...]

OPTIONS:
   --address value    Set the api address e.g 0.0.0.0:8080 [%MICRO_API_ADDRESS%]
   --handler value    Specify the request handler to be used for mapping HTTP requests to services; {api, event, http, rpc} [%MICRO_API_HANDLER%]
   --namespace value  Set the namespace used by the API e.g. com.example.api [%MICRO_API_NAMESPACE%]
   --resolver value   Set the hostname resolver used by the API {host, path, grpc} [%MICRO_API_RESOLVER%]
   --enable_rpc       Enable call the backend directly via /rpc [%MICRO_API_ENABLE_RPC%]

Translate

   --address value sets the ip and port that the gateway accesses, if set to 0.0.0.0:8080, then it can be accessed through http://127.0.0.1:8080/by default 0.0.0.0:8080
   --handler value specifies which type of handler to map to. You can choose {api, event, http, rpc} by default, RPC
   --namespace value specifies which microservices are exposed, and all microservices in that space can be accessed by namespace matching, such as specifying a value of `go.micro.srv'.
   --resolver value path and microservice correspondence, default is micro, optional is {host, path, grpc}
   --enable_rpc supports direct access through the rcp interface, default false

apihander

We map http to API type processing services using the --handler=api type option, which is explained below

  1. Download handlerapi.zip and unzip to%GOPATH%/techidea8.com/microapp/doc/. The unzipped directory is as follows
E:\winlion\gopath\src\techidea8.com\microapp\doc\handerapi>ls
go.mod  go.sum  handerapi.go  proto/
  1. Initialization module
#This step must be done or an error will occur`build command-line-arguments: cannot load techidea8.com/microapp/doc/handerapi/proto:`
>go mod init
>go: creating new go.mod: module techidea8.com/microapp/doc/handerapi
  1. To generate a proto file, replace the GOPATH path yourself.
>protoc --proto_path=E:/winlion/gopath/src --proto_path=. --go_out=. --micro_out=. proto/handerapi.proto
#Note that many documents on the network use--proto_path=import_proto_path:. This format specifies path, but it doesn't work in win10
#Another possible format is -IE:/winlion/gopath/src-I. The following is also possible 
>protoc -IE:/winlion/gopath/src -I. --go_out=. --micro_out=. proto/handerapi.proto
  1. Function
>go run handerapi.go
2019/08/24 20:59:32 Transport [http] Listening on [::]:54208
2019/08/24 20:59:32 Broker [http] Connected to [::]:54209
2019/08/24 20:59:32 Registry [mdns] Registering node: go.micro.api.example-71c8b1fa-f84b-4cf6-957f-617f67a4083c
  1. View service status
>micro list services
go.micro.api
go.micro.api.example
  1. test
>curl  "http://localhost:8080/example/example1/func1?name=winlion"
{"msg":"We have received your request winlion"}

eventhander

Publishing an event event is accomplished with the --handler=event option, and the key code is as follows

  1. Download handlerevent.zip and unzip it to%GOPATH%/techidea8.com/microapp/doc/. The unzipped directory is as follows
E:\winlion\gopath\src\techidea8.com\microapp\doc\handlerevent>ls
handlerevent.go

The core code is as follows

service := micro.NewService(micro.Name("test1"))
service.Init()
//Subscribe to the go.micro.evt.test event and note the test
micro.RegisterSubscriber("go.micro.evt.test", service.Server(), new(TestEvent))
if err := service.Run(); err != nil {
		log.Fatal(err)
}
  1. Running Services
>go run handlerevent.go
2019/08/24 23:17:18 Transport [http] Listening on [::]:57093
2019/08/24 23:17:18 Broker [http] Connected to [::]:57094
2019/08/24 23:17:19 Registry [mdns] Registering node: test1-7efd3b0a-5455-4456-870d-3b34e80f1354
2019/08/24 23:17:19 Subscribing test1-7efd3b0a-5455-4456-870d-3b34e80f1354 to topic: go.micro.evt.test
  1. View service status
>micro list services
go.micro.api
test1
topic:go.micro.evt.test
  1. Launch event publishing support
>micro api --handler=event --namespace=go.micro.evt
2019/08/24 23:06:28 Registering API Event Handler at /
2019/08/24 23:06:28 HTTP API Listening on [::]:8080
2019/08/24 23:06:28 Transport [http] Listening on [::]:56778
2019/08/24 23:06:28 Broker [http] Connected to [::]:56779
2019/08/24 23:06:28 Registry [mdns] Registering node: go.micro.api-c342fe3f-4a06-4955-be3f-79284e580467
  1. test
>curl -d "{\"message\": \"Hello,Winlion\"}" "http://localhost:8080/test/login" -X POST
#The server side displays the following data
>2019/08/24 23:18:54 Process Received Events login  {"message": "Hello,Winlion"}

Note that under the win system, publishing json data through curl requires double quotation marks and the escape character\ Be careful Test in http://localhost:8080/test/login corresponds to test in go.micro.evt.test

eventhander

Publishing an event event is accomplished with the --handler=event option, and the key code is as follows

  1. Download handlerevent.zip and unzip it to%GOPATH%/techidea8.com/microapp/doc/. The unzipped directory is as follows
E:\winlion\gopath\src\techidea8.com\microapp\doc\handlerevent>ls
handlerevent.go

The core code is as follows

service := micro.NewService(micro.Name("test1"))
service.Init()
//Subscribe to the go.micro.evt.test event and note the test
micro.RegisterSubscriber("go.micro.evt.test", service.Server(), new(TestEvent))
if err := service.Run(); err != nil {
		log.Fatal(err)
}
  1. Running Services
>go run handlerevent.go
2019/08/24 23:17:18 Transport [http] Listening on [::]:57093
2019/08/24 23:17:18 Broker [http] Connected to [::]:57094
2019/08/24 23:17:19 Registry [mdns] Registering node: test1-7efd3b0a-5455-4456-870d-3b34e80f1354
2019/08/24 23:17:19 Subscribing test1-7efd3b0a-5455-4456-870d-3b34e80f1354 to topic: go.micro.evt.test
  1. View service status
>micro list services
go.micro.api
test1
topic:go.micro.evt.test
  1. Launch event publishing support
>micro api --handler=event --namespace=go.micro.evt
2019/08/24 23:06:28 Registering API Event Handler at /
2019/08/24 23:06:28 HTTP API Listening on [::]:8080
2019/08/24 23:06:28 Transport [http] Listening on [::]:56778
2019/08/24 23:06:28 Broker [http] Connected to [::]:56779
2019/08/24 23:06:28 Registry [mdns] Registering node: go.micro.api-c342fe3f-4a06-4955-be3f-79284e580467
  1. test
>curl -d "{\"message\": \"Hello,Winlion\"}" "http://localhost:8080/test/login" -X POST
#The server side displays the following data
>2019/08/24 23:18:54 Process Received Events login  {"message": "Hello,Winlion"}

Note that under the win system, publishing json data through curl requires double quotation marks and the escape character\ Be careful Test in http://localhost:8080/test/login corresponds to test in go.micro.evt.test

rpchander

The mapping between http and RPC services is implemented by using the --handler=rpc type option. The RPC type is similar to the api type, referring to the apihanlder-related code. The rpchander code package is `handler rpc'.

  1. Download handlerrpc.zip and unzip it to%GOPATH%/techidea8.com/microapp/doc/. The unzipped directory is as follows
E:\winlion\gopath\src\techidea8.com\microapp\doc\handlerrpc>ls
handerapi.go  proto/
  1. Initialization module
#This step must be done or an error will occur`build command-line-arguments: cannot load techidea8.com/microapp/doc/handerapi/proto:`
>go mod init
>go: creating new go.mod: module techidea8.com/microapp/doc/handlerrpc
  1. To generate a proto file, replace the GOPATH path yourself.
>protoc --proto_path=. --go_out=. --micro_out=. proto/handlerrpc.proto
#Note that many documents on the network use--proto_path=import_proto_path:. This format specifies path, but it doesn't work in win10
#Another possible format is -IE:/winlion/gopath/src-I. The following is also possible 
>protoc -IE:/winlion/gopath/src -I. --go_out=. --micro_out=. proto/handerapi.proto
  1. Function
>go run handlerrpc.go
2019/08/24 20:59:32 Transport [http] Listening on [::]:54208
2019/08/24 20:59:32 Broker [http] Connected to [::]:54209
2019/08/24 20:59:32 Registry [mdns] Registering node: go.micro.api.example-71c8b1fa-f84b-4cf6-957f-617f67a4083c
  1. View service status
>micro list services
go.micro.api
go.micro.api.model1
  1. test
>curl -H "Content-Type: application/json" -d "{\"arg\": \"Winlion\"}" "http://localhost:8080/model1/model1/action1"
{"data":"Received data Winlion"}

The difference between RPC handler and api handler is that the data exchange proto model of api handler is encapsulated again on the basis of rpc.

httphander

With the--handler=http type option, HTTP service mapping, the core code is as follows

  • The new handlerweb.go code is as follows
//handlerweb.go
package main

import (
	"encoding/json"
	"log"
	"net/http"
	"github.com/micro/go-micro/web"
)
//hello handler, print helloworld
func hello(w http.ResponseWriter, req *http.Request) {
	//json support
	w.Header().Add("content-type", "application/json;charset=utf-8")
	if err := json.NewEncoder(w).Encode(map[string]interface{}{
		"code":    0,
		"message": "hello,world",
	}); err != nil {
    	//Page error display information
		http.Error(w, err.Error(), http.StatusNotFound)
	}
}

func main() {
	//new a web service
	service := web.NewService(web.Name("go.micro.web.hello"))
	//Binding Mapping Method
    service.HandleFunc("/", hello)
    //Initialization
	service.Init()
    //Function
	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}
  • Start application
>go run handlerweb.go
2019/08/24 23:58:14 Listening on [::]:57984
  • Start api service
>micro api --handler=http --namespace=go.micro.web
2019/08/24 23:58:42 Registering API HTTP Handler at /{service:[a-zA-Z0-9]+}
2019/08/24 23:58:42 HTTP API Listening on [::]:8080
2019/08/24 23:58:42 Transport [http] Listening on [::]:57992
2019/08/24 23:58:42 Broker [http] Connected to [::]:57993
2019/08/24 23:58:42 Registry [mdns] Registering node: go.micro.api-fecb79d6-0175-4d1c-9243-29c1d616b70d
  • test
>curl http://127.0.0.1:8080/hello/
{"code":0,"message":"hello,world"}
#Notice that hello corresponds to hello in microservice `go.micro.web.hello`

enable_rpc

This is to turn on direct access support for RPC and set enable_rpc=true to be accessible through the following interfaces

  • Turn on rpc support
>>micro api --handler=rpc --namespace=go.micro.api --enable_rpc=true
  • New Micro Service
>micro new --type=srv techidea8.com/microapp/doc/enablerpc
Creating service go.micro.srv.enablerpc in E:\winlion\gopath\src\techidea8.com\microapp\doc\e
                                                                                             
.                                                                                            
├── main.go                                                                                  
├── plugin.go                                                                                
├── handler                                                                                  
│   └── enablerpc.go                                                                         
├── subscriber                                                                               
│   └── enablerpc.go                                                                         
├── proto\enablerpc                                                                          
│   └── enablerpc.proto                                                                      
├── Dockerfile                                                                               
├── Makefile                                                                                 
├── README.md                                                                                
└── go.mod                                                                                   
                                                                                             
                                                                                             
download protobuf for micro:                                                                 
                                                                                             
brew install protobuf                                                                        
go get -u github.com/golang/protobuf/{proto,protoc-gen-go}                                   
go get -u github.com/micro/protoc-gen-micro                                                  
                                                                                             
compile the proto file enablerpc.proto:                                                      

                                                                                             
cd E:\winlion\gopath\src\techidea8.com\microapp\doc\enablerpc                                
protoc --proto_path=.:$GOPATH/src --go_out=. --micro_out=. proto/enablerpc/enablerpc.proto   
                                                                                             

Note that since it is not recognized under win--proto_path=.:$GOPATH/src, we need to process the following script by ourselves, where E:/winlion/gopath should be replaced with their respective GOPATH

>cd /d E:\winlion\gopath\src\techidea8.com\microapp\doc\enablerpc
>protoc --proto_path=. --proto_path=E:/winlion/gopath/src --go_out=. --micro_out=. proto/enablerpc/enablerpc.proto
  • Start Services
#Start Micro Service
>go run main.go
#Start rpc support
> micro api --handler=rpc --namespace=go.micro.srv --enable_rpc=true
  • test
> curl -H "Content-Type: application/json" -d "{\"service\": \"go.micro.srv.enablerpc\",\"method\": \"Enablerpc.Call\", \"request\": {\"name\": \"Winlion\"}}" "http://localhost:8080/rpc"
#Return the following data
{"msg":"Hello Winlion"}

You may need to read the following before reading this article

Go golang Distributed Micro Services Framework Go-microGetting Started Notes 1:1 Minute Quick Setup Go-microenvironment

Recommended reading

WeChat QR Code Enables Site Login to Provide Experience Address and Source Code

Open source project golang go language background management framework restgo-admin

Calendar plugin that supports gesture touch and slides left and right

18 Internet Business Models You Need to Know

Posted by runestation on Sat, 24 Aug 2019 17:50:17 -0700