MicroServices under Golang-part 6th-WEB Clients

Source: Internet
Author: User
Tags sprintf docker run
This is a creation in Article, where the information may have evolved or changed. In the previous article, we looked at some of the various event-driven methods that were generated using the Go-micro and go languages. In this article, we'll dive into the client and explore how to create a WEB client that interacts with the platform we created earlier. This article describes how to use the [micro] (HTTPS://GITHUB.COM/MICRO/MICRO) toolkit to generate a Web client from an external proxy internal RPC method. We will create a user interface to build the login interface for the platform, and also create an interface for using our consignments. This interface contains features such as creating users, logging in, and creating consignments. The previous articles in this series have already introduced some of the code, and in this article I will take you in-depth understanding. So let's get started! # # RPC Recovery rest has been serving the network for many years and quickly becomes a way to manage resources between clients and servers. REST is gradually replacing outdated RPC and SOAP. The era of having to write a WSDL file has passed. REST promises us a practical, simple and standardized approach to resource management. REST uses the HTTP protocol to define the specific Web action types that are being executed. REST encourages us to use HTTP error response codes to more accurately describe the server's response status. And in most cases, this method works well, and there is no problem. But like all good things, rest has a lot of shortcomings and drawbacks, and I'm not going to go into details here. Everyone is interested to refer to [this article] (https://medium.freecodecamp.org/rest-is-the-new-soap-97ff6c09896d). But! With the advent of * * Micro services, RPC is making a comeback. REST is useful for managing different resources, but microservices typically only handle a single resource, which makes it unnecessary for us to use RESTful terminology in the context of microservices. Instead, we can focus on a single, specific operation and interaction for each service. # # Micro We have used Go-micro extensively in this series of tutorials and now we will introduce the Micro CLI Toolkit. This micro toolkit provides features such as API gateways, Sidecar, Web proxies, and other cool features. But the main feature we use in this article is the API gateway. The API Gateway will allow us to call the RPC proxy as a Web-friendly Javascripton RPCCalled, and then exposes the URLs used in the client application. So how do these cool features work? First, make sure that the Micro Toolkit is installed: ' $ go get-u github.com/micro/micro ' in a better way to use micro in a Docker environment or recommend that you use a Docker image: ' $ docker pull Micro Hq/micro "The next step is to look at the code for the User Service, and I've made some modifications to the code for the User service:" ' go//shippy-user-service/main.gopackage mainimport ("Log" PB "Github.com/ewanvalentine/shippy-user-service/proto/auth" "Github.com/micro/go-micro" _ "Github.com/micro /go-plugins/registry/mdns ") Func main () {//created a database connection//The Main method ends before closing database connection db, err: = CreateConnection () defer D B.close () if err! = Nil {log. Fatalf ("Could not connect to DB:%v", err)}//automatically port the user struct type to the database type. This operation will do a detection of DB once every time the service is restarted. Automigrate (&AMP;PB. user{}) Repo: = &userrepository{db}tokenservice: = &tokenservice{repo}//Create a new service srv: = Micro. NewService (//The name must match micro in the package name you defined in the PROTOBUF definition. Name ("Shippy.auth"),//Init used to initialize the command line parameter srv. Init ()//Would comment this off for today to save have to run this locally ...//publisher: = Micro. Newpublisher ("user.created", srv. Client ())//NoteBook HANDLERPB. Registerauthhandler (SRV. Server (), &service{repo, Tokenservice, publisher})//start Serverif err: = srv. Run (); Err! = Nil {log. Fatal (Err)}} "" "c//shippy-user-service/proto/auth/auth.protosyntax =" Proto3 ";p ackage auth;service auth {RPC Create (user) returns (Response) {}rpc Get (user) returns (Response) {}rpc GetAll (Request) returns (Response) {}rpc Auth (use R) returns (token) {}rpc Validatetoken (token) returns (token) {}}message User {string id = 1;string name = 2;string Compan y = 3;string email = 4;string Password = 5;} Message Request {}message Response {User user = 1;repeated user users = 2;repeated Error errors = 3;} Message Token {String token = 1;bool valid = 2;repeated Error errors = 3;} Message Error {Int32 code = 1;string Description = 2;} "'" go//shippy-user-service/handler.gopackage mainimport ("Errors" "FMT" "Log" PB "github.com/ewanvalentine/ Shippy-user-service/proto/auth "Micro" Github.com/micro/go-micro "Golang.org/x/crypto/bcrypt" "golang.org/x/net/ Context ") const TOPIC = "user.created" type service struct {repo repositorytokenservice authablepublisher micro. Publisher}func (SRV *service) Get (CTX context. Context, req *PB. User, Res *PB. Response) Error {user, err: = Srv.repo.Get (req. ID) If err! = Nil {return err}res. User = Userreturn nil}func (SRV *service) GetAll (CTX context. Context, req *PB. Request, Res *PB. Response) Error {users, err: = Srv.repo.GetAll () if err! = Nil {return err}res. Users = Usersreturn nil}func (SRV *service) Auth (CTX context. Context, req *PB. User, Res *PB. Token) Error {log. Println ("Logging in with:", req. Email, req. Password) User, err: = Srv.repo.GetByEmail (req. Email) log. Println (user, err) if err! = Nil {return err}//compares the password entered with the hash password stored in the database if err: = Bcrypt.comparehashandpassword ([]byte (user. Password), []byte (req. Password)); Err! = Nil {return Err}token, err: = Srv.tokenService.Encode (user) if err! = Nil {return err}res. Token = Tokenreturn nil}func (SRV *service) Create (CTX context. Context, req *PB. User, Res *PB. Response) Error {log. PRintln ("Creating User:", req)//Generate a hash value for our password Hashedpass, err: = Bcrypt. Generatefrompassword ([]byte (req. Password), Bcrypt. Defaultcost) If err! = Nil {return errors. New (FMT. Sprintf ("Error hashing Password:%v", err))}req. Password = string (hashedpass) If err: = Srv.repo.Create (req); Err! = Nil {return errors. New (FMT. Sprintf ("Error creating User:%v", err))}res. User = Reqif Err: = srv. Publisher.publish (CTX, req); Err! = Nil {return errors. New (FMT. Sprintf ("Error publishing event:%v", err))}return Nil}func (SRV *service) Validatetoken (CTX context. Context, req *PB. Token, Res *PB. Token) Error {//Decode tokenclaims, err: = Srv.tokenService.Decode (req. Token) If err! = Nil {return err}if claims. User.ID = = "" {return errors. New ("Invalid user")}res. Valid = Truereturn Nil} ' ' Now run ' make build && make run '. Then go to Shippy-email-service Run ' make build && make run '. Once both services are running, run: ' shell$ Docker run-p 8080:8080 \ e micro_registry=mdns \microhq/micro API \--handler=rpc \--address=:80 80 \--namespace=shippy "This will open a 8080 port in the Docker container, exposing the micro Api-gateway as an RPC handler, using MDNs as the local registry, using the namespace Shippy,s Hippy is the first part of all our service names. such as Shippy.auth or Shippy.email. It is important to set it up because it defaults to GO.MICRO.API, and by default, GO.MICRO.API is unable to find the specific service we need to proxy. We can now call our User Service method using the following method: Create a User: ' Shellcurl-xpost-h ' Content-type:application/javascripton ' \-d ' {"Service": " Shippy.auth "," Method ":" Auth.create "," request ": {" user ": {" email ":" ewan.valentine89@gmail.com "," Password ":" Testing123 "," name ":" Ewan Valentine "," Company ":" BBC "}} ' \ Http://localhost:8080/rpc '" This request contains the name of the service we want to send to, The service method to use, and the service data. Verify User: "' shell$ curl-xpost-h ' Content-type:application/javascripton ' \ d ' {" Service ":" Shippy.auth "," Method ":" Auth.a Uth "," request ": {" email ":" your@email.com "," Password ":" Somepass "}} ' \http://localhost:8080/rpc" ' # # Consignment Ser Vice now launches our consignment service again, ' make build && make run '. We don't need to change anything here, but if we run the RPC agent we should also create a consignment: "' shell$ curl-xpost-h ' content-Type:application/javascripton '-d ' {"Service": "Shippy.consignment", "Method": "Consignmentservice.create", " Request ": {" description ":" This is a test "," Weight ":" $ "," containers ": []} '--url http://localhost:8080/rpc '" # # Vessel Service finally in order to test the user interface interface, we need to run the Vessel services, there is no change to the code, directly run ' make build && do run '. # # User interface can now create a user interface using the new RPC node that we just created. This article uses React, but you can use the rest of the architecture if you like. The requests are all the same. This article uses the React-create-app Library from Facebook: ' $ react-create-app shippy-ui ' after the installation of ' $ NPM install-g React-create-app ' was completed. This will create a framework for your React application. "' javascript//shippy-ui/src/app.javascriptimport React, {Component} from ' React '; Import './app.css '; import Createconsignment from './createconsignment ', import authenticate from './authenticate '; class App extends Component { State = {Err:null,authenticated:false,}onauth = (token) + {this.setstate ({authenticated:true,});} Renderlogin = () = {return (<authenticate Onauth={this.onauth}/>);} renderauthenticated = () = {return (<createconsignment/>);} GetToken = () = {return Localstorage.getitem (' token ') | | false;} IsAuthenticated = () = {return this.state.authenticated | | this.gettoken () | | false;} Render () {Const authenticated = this.isauthenticated (); return (<div classname= "App" ><div classname= " App-header ">

via:https://ewanvalentine.io/microservices-in-golang-part-6/

Author: Andrécarvalho Translator: ZHANGYANG9 proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

701 Reads ∙1 likes
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.