we looked at some of the various approaches to event-driven architecture in go-micro and in go in general. This part, we're going to delve into the client side and take a look at how we can create web clients which interact with our platform.

We'll take a look at how micro toolkit, enables you to proxy your internal rpc methods externally to web clients.

We'll be creating a user interfaces for our platform, a login screen, and a create consignment interface. This will tie together some of the previous posts.

So let's begin!

REST has served the web well for many years now, and it has rapidly become the goto way of managing resources between clients and servers. REST came about to replace a wild west of RPC and SOAP implementations, which felt dated and painful at times. Ever had to write a wsdl file? eye roll.

REST promised us a pragmatic, simple, and unified approach to managing resources. REST used http verbs to be more explicit in the type of action being performed. REST encouraged us to use http error codes to better describe the response from the server. And for the most part, this approach worked well, and was fine. But like all good things, REST had many gripes and annoyances, that I'm not going to detail in full here. But do give a read. But RPC is making a comeback with the advent of microservices.

Rest is great for managing different resources, but a microservice typically only deals with a single resource by its very nature. So we don't need to use RESTful terminology in the context of microservices. Instead we can focus on specific actions and interactions with each service.

We've been using go-micro extensively throughout this tutorial, we'll now touch on the micro cli/toolkit. The micro toolkit provides an API gateway, a sidecar, a web proxy, and a few other cool features. But the main part we'll be looking at in this post is the API gateway.

The API gateway will allow us to proxy our rpc calls to web friendly JSON rpc calls, and will expose urls which we can use in our client side applications.

So how does this work? You firstly ensure that you have the micro toolkit installed:

Now let's head into our user service, I made a few changes, mostly error handling and naming conventions:

  1. // shippy-user-service/main.go
  2. package main
  3. import (
  4. "log"
  5. pb "github.com/EwanValentine/shippy-user-service/proto/auth"
  6. "github.com/micro/go-micro"
  7. _ "github.com/micro/go-plugins/registry/mdns"
  8. )
  9. func main() {
  10. // Creates a database connection and handles
  11. // closing it again before exit.
  12. db, err := CreateConnection()
  13. defer db.Close()
  14. if err != nil {
  15. log.Fatalf("Could not connect to DB: %v", err)
  16. }
  17. // Automatically migrates the user struct
  18. // into database columns/types etc. This will
  19. // check for changes and migrate them each time
  20. // this service is restarted.
  21. db.AutoMigrate(&pb.User{})
  22. repo := &UserRepository{db}
  23. tokenService := &TokenService{repo}
  24. // Create a new service. Optionally include some options here.
  25. srv := micro.NewService(
  26. // This name must match the package name given in your protobuf definition
  27. micro.Name("shippy.auth"),
  28. )
  29. // Init will parse the command line flags.
  30. srv.Init()
  31. // Will comment this out for now to save having to run this locally...
  32. // publisher := micro.NewPublisher("user.created", srv.Client())
  33. // Register handler
  34. pb.RegisterAuthHandler(srv.Server(), &service{repo, tokenService, publisher})
  35. // Run the server
  36. if err := srv.Run(); err != nil {
  37. log.Fatal(err)
  38. }
  39. }
  1. // shippy-user-service/proto/auth/auth.proto
  2. syntax = "proto3";
  3. package auth;
  4. service Auth {
  5. rpc Create(User) returns (Response) {}
  6. rpc Get(User) returns (Response) {}
  7. rpc GetAll(Request) returns (Response) {}
  8. rpc Auth(User) returns (Token) {}
  9. rpc ValidateToken(Token) returns (Token) {}
  10. }
  11. message User {
  12. string id = 1;
  13. string name = 2;
  14. string company = 3;
  15. string email = 4;
  16. string password = 5;
  17. }
  18. message Request {}
  19. message Response {
  20. User user = 1;
  21. repeated User users = 2;
  22. repeated Error errors = 3;
  23. }
  24. message Token {
  25. string token = 1;
  26. bool valid = 2;
  27. repeated Error errors = 3;
  28. }
  29. message Error {
  30. int32 code = 1;
  31. string description = 2;
  32. }

And…

Now run $ make build && make run. Then head over to your shippy-email-service and run $ make build && make run. Once both of these are running, run:

  1. $ docker run -p 8080:8080 \
  2. -e MICRO_REGISTRY=mdns \
  3. microhq/micro api \
  4. --handler=rpc \
  5. --address=:8080 \
  6. --namespace=shippy

This runs the micro api-gateway as an rpc handler on port 8080 in a Docker container. We're telling it to use mdns as our registry locally, the same as our other services. Finally, we're telling it to use the namespace shippy, this is the first part of all of our service names. I.e shippy.auth or shippy.email. It's important to set this as it defaults to go.micro.api, in which case, it won't be able to find our services in order to proxy them.

Our user service methods can now be called using the following:

Create a user:

  1. curl -XPOST -H 'Content-Type: application/json' \
  2. -d '{ "service": "shippy.auth", "method": "Auth.Create", "request": { "user": { "email": "[email protected]", "password": "testing123", "name": "Ewan Valentine", "company": "BBC" } } }' \
  3. http://localhost:8080/rpc

As you can see, we include in our request, the service we want to be routed to, the method on that service we want to use, and finally the data we wish to be used.

Authenticate a user:

  1. $ curl -XPOST -H 'Content-Type: application/json' \
  2. -d '{ "service": "shippy.auth", "method": "Auth.Auth", "request": { "email": "", "password": "SomePass" } }' \
  3. http://localhost:8080/rpc

Great!

Now it's time to fire up our consignment service again, $ make build && make run. We shouldn't need to change anything here, but, running the rpc proxy, we should be able to do:

The final service we will need to run in order to test our user interface, is our vessel service, nothing's changed here eiter, so just run $ make build && make run.

Let's make use of our new rpc endpoints, and create a UI. We're going to be using React, but feel free to use whatever you like. The requests are all the same. I'm going to be using the react-create-app library from Facebook. $ npm install -g react-create-app. Once that's installed you can do $ react-create-app shippy-ui. And that will create the skeleton of a React application for you.

So let's begin…

  1. // shippy-ui/src/App.js
  2. import React, { Component } from 'react';
  3. import './App.css';
  4. import CreateConsignment from './CreateConsignment';
  5. import Authenticate from './Authenticate';
  6. class App extends Component {
  7. state = {
  8. err: null,
  9. authenticated: false,
  10. }
  11. onAuth = (token) => {
  12. this.setState({
  13. authenticated: true,
  14. });
  15. }
  16. renderLogin = () => {
  17. return (
  18. <Authenticate onAuth={this.onAuth} />
  19. );
  20. }
  21. renderAuthenticated = () => {
  22. return (
  23. );
  24. }
  25. return localStorage.getItem('token') || false;
  26. }
  27. isAuthenticated = () => {
  28. return this.state.authenticated || this.getToken() || false;
  29. }
  30. render() {
  31. const authenticated = this.isAuthenticated();
  32. return (
  33. <div className="App">
  34. <div className="App-header">
  35. <h2>Shippy</h2>
  36. </div>
  37. <div className='App-intro container'>
  38. {(authenticated ? this.renderAuthenticated() : this.renderLogin())}
  39. </div>
  40. </div>
  41. );
  42. }
  43. }
  44. export default App;

Now let's add our main two components, Authenticate and CreateConsignment:

  1. // shippy-ui/src/Authenticate.js
  2. import React from 'react';
  3. class Authenticate extends React.Component {
  4. constructor(props) {
  5. super(props);
  6. }
  7. state = {
  8. authenticated: false,
  9. email: '',
  10. password: '',
  11. err: '',
  12. }
  13. login = () => {
  14. fetch(`http://localhost:8080/rpc`, {
  15. method: 'POST',
  16. headers: {
  17. 'Content-Type': 'application/json',
  18. },
  19. body: JSON.stringify({
  20. request: {
  21. email: this.state.email,
  22. password: this.state.password,
  23. },
  24. service: 'shippy.auth',
  25. method: 'Auth.Auth',
  26. }),
  27. })
  28. .then(res => res.json())
  29. .then(res => {
  30. this.props.onAuth(res.token);
  31. this.setState({
  32. token: res.token,
  33. authenticated: true,
  34. });
  35. })
  36. .catch(err => this.setState({ err, authenticated: false, }));
  37. }
  38. signup = () => {
  39. fetch(`http://localhost:8080/rpc`, {
  40. method: 'POST',
  41. headers: {
  42. 'Content-Type': 'application/json',
  43. },
  44. body: JSON.stringify({
  45. request: {
  46. email: this.state.email,
  47. password: this.state.password,
  48. name: this.state.name,
  49. },
  50. method: 'Auth.Create',
  51. service: 'shippy.auth',
  52. }),
  53. })
  54. .then((res) => res.json())
  55. .then((res) => {
  56. this.props.onAuth(res.token.token);
  57. this.setState({
  58. token: res.token.token,
  59. authenticated: true,
  60. });
  61. localStorage.setItem('token', res.token.token);
  62. })
  63. .catch(err => this.setState({ err, authenticated: false, }));
  64. }
  65. setEmail = e => {
  66. this.setState({
  67. email: e.target.value,
  68. });
  69. }
  70. setPassword = e => {
  71. this.setState({
  72. password: e.target.value,
  73. });
  74. }
  75. setName = e => {
  76. this.setState({
  77. name: e.target.value,
  78. });
  79. }
  80. render() {
  81. return (
  82. <div className='Authenticate'>
  83. <div className='Login'>
  84. <div className='form-group'>
  85. <input
  86. type="email"
  87. onChange={this.setEmail}
  88. placeholder='E-Mail'
  89. className='form-control' />
  90. </div>
  91. <div className='form-group'>
  92. <input
  93. type="password"
  94. onChange={this.setPassword}
  95. placeholder='Password'
  96. className='form-control' />
  97. </div>
  98. <button className='btn btn-primary' onClick={this.login}>Login</button>
  99. <br /><br />
  100. </div>
  101. <div className='Sign-up'>
  102. <div className='form-group'>
  103. <input
  104. type='input'
  105. onChange={this.setName}
  106. placeholder='Name'
  107. </div>
  108. <input
  109. type='email'
  110. onChange={this.setEmail}
  111. placeholder='E-Mail'
  112. className='form-control' />
  113. </div>
  114. <div className='form-group'>
  115. <input
  116. type='password'
  117. onChange={this.setPassword}
  118. placeholder='Password'
  119. className='form-control' />
  120. </div>
  121. <button className='btn btn-primary' onClick={this.signup}>Sign-up</button>
  122. </div>
  123. </div>
  124. );
  125. }
  126. }
  127. export default Authenticate;

and…

  1. // shippy-ui/src/CreateConsignment.js
  2. import React from 'react';
  3. import _ from 'lodash';
  4. class CreateConsignment extends React.Component {
  5. constructor(props) {
  6. super(props);
  7. }
  8. state = {
  9. created: false,
  10. description: '',
  11. weight: 0,
  12. containers: [],
  13. consignments: [],
  14. }
  15. componentWillMount() {
  16. fetch(`http://localhost:8080/rpc`, {
  17. method: 'POST',
  18. headers: {
  19. 'Content-Type': 'application/json',
  20. },
  21. body: JSON.stringify({
  22. service: 'shippy.consignment',
  23. method: 'ConsignmentService.Get',
  24. request: {},
  25. })
  26. })
  27. .then(req => req.json())
  28. .then((res) => {
  29. this.setState({
  30. consignments: res.consignments,
  31. });
  32. });
  33. }
  34. create = () => {
  35. const consignment = this.state;
  36. fetch(`http://localhost:8080/rpc`, {
  37. method: 'POST',
  38. headers: {
  39. 'Content-Type': 'application/json',
  40. },
  41. body: JSON.stringify({
  42. service: 'shippy.consignment',
  43. method: 'ConsignmentService.Create',
  44. request: _.omit(consignment, 'created', 'consignments'),
  45. }),
  46. })
  47. .then((res) => res.json())
  48. .then((res) => {
  49. this.setState({
  50. created: res.created,
  51. consignments: [...this.state.consignments, consignment],
  52. });
  53. });
  54. }
  55. addContainer = e => {
  56. this.setState({
  57. containers: [...this.state.containers, e.target.value],
  58. });
  59. }
  60. setDescription = e => {
  61. this.setState({
  62. description: e.target.value,
  63. });
  64. }
  65. setWeight = e => {
  66. this.setState({
  67. weight: Number(e.target.value),
  68. });
  69. }
  70. render() {
  71. const { consignments, } = this.state;
  72. return (
  73. <div className='consignment-screen'>
  74. <div className='consignment-form container'>
  75. <br />
  76. <div className='form-group'>
  77. <textarea onChange={this.setDescription} className='form-control' placeholder='Description'></textarea>
  78. </div>
  79. <div className='form-group'>
  80. <input onChange={this.setWeight} type='number' placeholder='Weight' className='form-control' />
  81. </div>
  82. <div className='form-control'>
  83. Add containers...
  84. </div>
  85. <br />
  86. <button onClick={this.create} className='btn btn-primary'>Create</button>
  87. <br />
  88. <hr />
  89. </div>
  90. {(consignments && consignments.length > 0
  91. ? <div className='consignment-list'>
  92. <h2>Consignments</h2>
  93. {consignments.map((item) => (
  94. <div>
  95. <p>Vessel id: {item.vessel_id}</p>
  96. <p>Consignment id: {item.id}</p>
  97. <p>Description: {item.description}</p>
  98. <p>Weight: {item.weight}</p>
  99. <hr />
  100. </div>
  101. ))}
  102. </div>
  103. : false)}
  104. </div>
  105. );
  106. }
  107. }
  108. export default CreateConsignment;

Note: I also added Twitter Bootstrap into /public/index.html and altered some of the css.

Now run the user interface . This should automatically open within your browser. You should now be able to sign-up and log-in and view a consignment form where you can create new consignments. Take a look in the network tab in your dev tools, and take a look at the rpc methods firing and fetching our data from our different microservices.

That's the end of part 6, as ever, any feedback, please do drop me an email and I'll reply as fast as I can (which sometimes isn't that fast, please bare with me).

If you are finding this series useful, and you use an ad-blocker (who can blame you). Please consider chucking me a couple of quid for my time and effort. Cheers!

Or, sponsor me on Patreon to support more content like this.