Sponsor me on Patreon to support more content like this.

In the previous post 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!

The RPC renaissance

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 this article 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.

Micro

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:

  1. $ go get -u github.com/micro/micro

Better still, since we're using Docker, let's use the docker image:

  1. $ docker pull microhq/micro

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…

  1. // shippy-user-service/handler.go
  2. package main
  3. import (
  4. "errors"
  5. "fmt"
  6. "log"
  7. pb "github.com/EwanValentine/shippy-user-service/proto/auth"
  8. micro "github.com/micro/go-micro"
  9. "golang.org/x/crypto/bcrypt"
  10. "golang.org/x/net/context"
  11. )
  12. const topic = "user.created"
  13. type service struct {
  14. repo Repository
  15. tokenService Authable
  16. Publisher micro.Publisher
  17. }
  18. func (srv *service) Get(ctx context.Context, req *pb.User, res *pb.Response) error {
  19. user, err := srv.repo.Get(req.Id)
  20. if err != nil {
  21. return err
  22. }
  23. res.User = user
  24. return nil
  25. }
  26. func (srv *service) GetAll(ctx context.Context, req *pb.Request, res *pb.Response) error {
  27. users, err := srv.repo.GetAll()
  28. if err != nil {
  29. return err
  30. }
  31. res.Users = users
  32. return nil
  33. }
  34. func (srv *service) Auth(ctx context.Context, req *pb.User, res *pb.Token) error {
  35. log.Println("Logging in with:", req.Email, req.Password)
  36. user, err := srv.repo.GetByEmail(req.Email)
  37. log.Println(user, err)
  38. if err != nil {
  39. return err
  40. }
  41. // Compares our given password against the hashed password
  42. // stored in the database
  43. if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
  44. return err
  45. }
  46. token, err := srv.tokenService.Encode(user)
  47. if err != nil {
  48. return err
  49. }
  50. res.Token = token
  51. return nil
  52. }
  53. func (srv *service) Create(ctx context.Context, req *pb.User, res *pb.Response) error {
  54. log.Println("Creating user: ", req)
  55. // Generates a hashed version of our password
  56. hashedPass, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
  57. if err != nil {
  58. return errors.New(fmt.Sprintf("error hashing password: %v", err))
  59. }
  60. req.Password = string(hashedPass)
  61. if err := srv.repo.Create(req); err != nil {
  62. return errors.New(fmt.Sprintf("error creating user: %v", err))
  63. }
  64. res.User = req
  65. if err := srv.Publisher.Publish(ctx, req); err != nil {
  66. return errors.New(fmt.Sprintf("error publishing event: %v", err))
  67. }
  68. return nil
  69. }
  70. func (srv *service) ValidateToken(ctx context.Context, req *pb.Token, res *pb.Token) error {
  71. // Decode token
  72. claims, err := srv.tokenService.Decode(req.Token)
  73. if err != nil {
  74. return err
  75. }
  76. if claims.User.Id == "" {
  77. return errors.New("invalid user")
  78. }
  79. res.Valid = true
  80. return nil
  81. }

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": "[email protected]", "password": "SomePass" } }' \
  3. http://localhost:8080/rpc

Great!

Consignment service

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:

Create a consignment:

  1. $ curl -XPOST -H 'Content-Type: application/json' \
  2. -d '{
  3. "service": "shippy.consignment",
  4. "method": "ConsignmentService.Create",
  5. "request": {
  6. "description": "This is a test",
  7. "weight": "500",
  8. "containers": []
  9. }
  10. }' --url http://localhost:8080/rpc

Vessel service

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.

User interface

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. <CreateConsignment />
  24. );
  25. }
  26. getToken = () => {
  27. return localStorage.getItem('token') || false;
  28. }
  29. isAuthenticated = () => {
  30. return this.state.authenticated || this.getToken() || false;
  31. }
  32. render() {
  33. const authenticated = this.isAuthenticated();
  34. return (
  35. <div className="App">
  36. <div className="App-header">
  37. <h2>Shippy</h2>
  38. </div>
  39. <div className='App-intro container'>
  40. {(authenticated ? this.renderAuthenticated() : this.renderLogin())}
  41. </div>
  42. </div>
  43. );
  44. }
  45. }
  46. 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. className='form-control' />
  108. </div>
  109. <div className='form-group'>
  110. <input
  111. type='email'
  112. onChange={this.setEmail}
  113. placeholder='E-Mail'
  114. className='form-control' />
  115. </div>
  116. <div className='form-group'>
  117. <input
  118. type='password'
  119. onChange={this.setPassword}
  120. placeholder='Password'
  121. className='form-control' />
  122. </div>
  123. <button className='btn btn-primary' onClick={this.signup}>Sign-up</button>
  124. </div>
  125. </div>
  126. );
  127. }
  128. }
  129. 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 $ npm start. 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! https://monzo.me/ewanvalentine

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