How to do it…

  1. Create a reactjs-client directory where we will keep all our ReactJS source files and an HTTP server, as follows:
$ mkdir reactjs-client && cd reactjs-client && touch server.go
  1. Copy the following code to server.go:
package main
import
(
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
type Route struct
{
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
var routes = Routes
{
Route
{
"getEmployees",
"GET",
"/employees",
getEmployees,
},
Route
{
"addEmployee",
"POST",
"/employee/add",
addEmployee,
},
}
type Employee struct
{
Id string `json:"id"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
}
type Employees []Employee
var employees []Employee
func init()
{
employees = Employees
{
Employee{Id: "1", FirstName: "Foo", LastName: "Bar"},
Employee{Id: "2", FirstName: "Baz", LastName: "Qux"},
}
}
func getEmployees(w http.ResponseWriter, r *http.Request)
{
json.NewEncoder(w).Encode(employees)
}
func addEmployee(w http.ResponseWriter, r *http.Request)
{
employee := Employee{}
err := json.NewDecoder(r.Body).Decode(&employee)
if err != nil
{
log.Print("error occurred while decoding employee
data :: ", err)
return
}
log.Printf("adding employee id :: %s with firstName
as :: %s and lastName as :: %s ", employee.Id,
employee.FirstName, employee.LastName)
employees = append(employees, Employee{Id: employee.Id,
FirstName: employee.FirstName, LastName: employee.LastName})
json.NewEncoder(w).Encode(employees)
}
func AddRoutes(router *mux.Router) *mux.Router
{
for _, route := range routes
{
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(route.HandlerFunc)
}
return router
}
func main()
{
muxRouter := mux.NewRouter().StrictSlash(true)
router := AddRoutes(muxRouter)
router.PathPrefix("/").Handler(http.FileServer
(http.Dir("./assets/")))
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, router)
if err != nil
{
log.Fatal("error starting http server :: ", err)
return
}
}
  1. Create another directory with the name assets where all our frontend code files, such as .html.js.css, and images will be kept, as follows:
$ mkdir assets && cd assets && touch index.html
  1. Copy the following content to index.html:
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>ReactJS Client</title>
</head>
<body>
<div id="react"></div>
<script src="/script.js"></script>
  </body>
</html>
  1. Move to the reactjs-client directory and execute npm init to create package.json where we specify all the dependencies required to build our react client such as React, React DOM, Webpack, Babel Loader, Babel Core, Babel Preset: ES2015, and Babel Preset: React, as follows:
$ cd reactjs-client && touch npm init

Replace the content of package.json with the following content:

{
"name": "reactjs-client",
"version": "1.0.0",
"description": "ReactJs Client",
"keywords":
[
"react"
],
"author": "Arpit Aggarwal",
"dependencies":
{
"axios": "^0.18.0",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-router-dom": "^4.2.2",
"webpack": "^4.2.0",
"webpack-cli": "^2.0.9",
"lodash": "^4.17.5"
},
"scripts":
{
"build": "webpack",
"watch": "webpack --watch -d"
},
"devDependencies":
{
"babel-core": "^6.18.2",
"babel-loader": "^7.1.4",
"babel-polyfill": "^6.16.0",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0"
}
}
  1. Create webpack.config.js where we will configure webpack, as follows:
$ cd reactjs-client && touch webpack.config.js

Copy the following content to webpack.config.js:

var path = require('path');
module.exports =
{
resolve:
{
extensions: ['.js', '.jsx']
},
mode: 'development',
entry: './app/main.js',
cache: true,
output:
{
path: __dirname,
filename: './assets/script.js'
},
module:
{
rules:
[
{
test: path.join(__dirname, '.'),
exclude: /(node_modules)/,
loader: 'babel-loader',
query:
{
cacheDirectory: true,
presets: ['es2015', 'react']
}
}
]
}
};
  1. Create an entry point for the webpack, which is reactjs-client/app/main.js by executing the following commands:
$ cd reactjs-client && mkdir app && cd app && touch main.js

Copy the following content to main.js:

'use strict';
const React = require('react');
const ReactDOM = require('react-dom')
import EmployeeApp from './components/employee-app.jsx'
ReactDOM.render
(
<EmployeeApp />,
document.getElementById('react')
)
  1. Define ReactApp along with its child components by executing the following commands:
$ cd reactjs-client && mkdir components && cd components && touch react-app.jsx employee-list.jsx employee.jsx add-employee.jsx

Copy the following content to reactjs-client/app/components/employee-app.jsx:

'use strict';
const React = require('react');
var axios = require('axios');
import EmployeeList from './employee-list.jsx'
import AddEmployee from './add-employee.jsx'
export default class EmployeeApp extends React.Component
{
constructor(props)
{
super(props);
this.state = {employees: []};
this.addEmployee = this.addEmployee.bind(this);
this.Axios = axios.create
(
{
headers: {'content-type': 'application/json'}
}
);
}
componentDidMount()
{
let _this = this;
this.Axios.get('/employees')
.then
(
function (response)
{
_this.setState({employees: response.data});
}
)
.catch(function (error) { });
}
addEmployee(employeeName)
{
let _this = this;
this.Axios.post
(
'/employee/add',
{
firstName: employeeName
}
)
.then
(
function (response)
{
_this.setState({employees: response.data});
}
)
.catch(function (error) { });
}
render()
{
return
(
<div>
<AddEmployee addEmployee={this.addEmployee}/>
<EmployeeList employees={this.state.employees}/>
</div>
)
}
}

Copy the following content to reactjs-client/app/components/employee.jsx:

const React = require('react');
export default class Employee extends React.Component
{
render()
{
return
(
<tr>
<td>{this.props.employee.firstName}</td>
</tr>
)
}
}

Copy the following content to reactjs-client/app/components/employee-list.jsx:

const React = require('react');
import Employee from './employee.jsx'
export default class EmployeeList extends React.Component
{
render()
{
var employees = this.props.employees.map
(
(employee, i) =>
<Employee key={i} employee={employee}/>
);
return
(
<table>
<tbody>
<tr>
<th>FirstName</th>
</tr>
{employees}
</tbody>
</table>
)
}
}

Copy the following content to reactjs-client/app/components/add-employee.jsx:

import React, { Component, PropTypes } from 'react'
export default class AddEmployee extends React.Component
{
render()
{
return
(
<div>
<input type = 'text' ref = 'input' />
<button onClick = {(e) => this.handleClick(e)}>
Add
</button>
</div>
)
}
handleClick(e)
{
const node = this.refs.input
const text = node.value.trim()
this.props.addEmployee(text)
node.value = ''
}
}

With everything in place, the directory structure should look like the following:

Directory structure
  1. Move to the reactjs-client directory and execute the following commands to install node modules and build webpack:
$ npm install
$ npm run build
  1. Run the program with the following command: 
$ go run server.go
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.15.99