<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Francis Sunday on Medium]]></title>
        <description><![CDATA[Stories by Francis Sunday on Medium]]></description>
        <link>https://medium.com/@codehakase?source=rss-38ef9ca6edc2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5SFO11u_Im1FBwkyGdziDw.jpeg</url>
            <title>Stories by Francis Sunday on Medium</title>
            <link>https://medium.com/@codehakase?source=rss-38ef9ca6edc2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 18:23:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codehakase/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[XXI]]></title>
            <link>https://medium.com/@codehakase/xxi-e3bc5eb39f65?source=rss-38ef9ca6edc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3bc5eb39f65</guid>
            <category><![CDATA[birthday]]></category>
            <dc:creator><![CDATA[Francis Sunday]]></dc:creator>
            <pubDate>Fri, 30 Nov 2018 23:47:21 GMT</pubDate>
            <atom:updated>2018-12-01T08:26:04.077Z</atom:updated>
            <content:encoded><![CDATA[<p>I spent a good part of 20 living in complete solitary yeesh!</p><p>Moved to Lagos, the city of stress, where I knew less than a handful of people, lost the zeal to communicate with people or with friends (the few I had).</p><p>There were times where I didn’t feel so lonely, but it was only for a short while 😔, I still slid back into solitary 😩.</p><p>In one year, I’ve really become a better person. I’m more exposed than most<br>people my age, everything peaked within this period, I got to experience some of the bullshit adulthood (found out I’ve been played, its a scam) had to offer, went broke a couple of times due to bad decisions, spent money on silly things I regretted a few moments later, you can say I fucked up a couple of times.</p><p>The past year nevertheless, was a great one, I’m still in awe about how I was able to survive through, and also the things I was able to achieve. My career as a software engineer peaked between this period, I met wonderful people, got to work on a shit load of interesting stuff, grew my network (as they say, your network kinda depicts your net-worth), got to positions I didn’t imagine myself being at this point in life, made my first Million (💸Whoop! Whoop!!), and yeah I grew some cool locks too 😁.</p><p>I’m 21 today, (heck yeah! 🎉🎉🎉) and looking back to my last birthday, and<br>conversations I had with myself on what I’d like to set in place before this<br>birthday, I’m super proud of myself, my parents are still in awe how I was able<br>to pull this off lol, haven’t asked for a dime since I was 19, moved out (yeah I miss home bruh), paid my own rent, bought my own meals (yeah I didn’t eat healthy most time yuck!), paid my own tuitions, dammmn! Man’s been busy, that means people’s prayers on my head have been working!!</p><p>I’m super grateful to the people that came into my life within this period, some of which I’ve grown a strong bond and connection with, hope they remember my birthday too lol.</p><p>For the next year, I pretty much want to work on myself. Need to kill off the<br>solitude lifestyle, and learn to be more social, maybe find love (who knows 😉).</p><p>Happy Birthday, Francis, you’ve been great!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3bc5eb39f65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a web app with Go, Gin, and React]]></title>
            <link>https://medium.com/free-code-camp/how-to-build-a-web-app-with-go-gin-and-react-cffdc473576?source=rss-38ef9ca6edc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/cffdc473576</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Francis Sunday]]></dc:creator>
            <pubDate>Tue, 08 May 2018 18:56:24 GMT</pubDate>
            <atom:updated>2018-05-08T18:56:24.777Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*zGDYRCxNPHUPcTowYotCdQ.png" /></figure><blockquote><em>This article was originally posted on </em><a href="https://hakaselogs.me/2018-04-20/building-a-web-app-with-go-gin-and-react"><em>My Blog</em></a></blockquote><p><strong>TL;DR:</strong> In this tutorial, I’ll show you how easy it is to build a web application with Go and the Gin framework and add authentication to it. Check out the Github <a href="https://github.com/codehakase/golang-gin">repo</a> for the code we’re going to write.</p><p><strong>Gin</strong> is a high-performance micro-framework. It delivers a very minimalistic framework that carries with it only the most essential features, libraries, and functionalities needed to build web applications and microservices. It makes it simple to build a request handling pipeline from modular, reusable pieces. It does this by allowing you to write middleware that can be plugged into one or more request handlers or groups of request handlers.</p><h3>Gin features</h3><p>Gin is a fast, simple yet fully featured and very efficient web framework for Go. Check out some of the features below that make it a worthy framework to consider for your next Golang project.</p><ul><li><strong>Speed:</strong> Gin is built for speed. The framework offers a Radix tree based routing and small memory footprint. No reflection. Predictable API performance.</li><li><strong>Crash-Free</strong>: Gin has the capability of catching crashes or panics during runtime, and can recover from them. This way your application will always be available.</li><li><strong>Routing:</strong> Gin provides a routing interface to allow you to express how your web application or API routes should look.</li><li><strong>JSON Validation:</strong> Gin can parse and validate JSON requests easily, checking for the existence of required values.</li><li><strong>Error Management:</strong> Gin provides a convenient way to collect all the errors occurred during a HTTP request. Eventually, a middleware can write them to a log file or to a database and send them through the network.</li><li><strong>Built-In Rendering:</strong> Gin provides an easy to use API for JSON, XML, and HTML rendering.</li></ul><h3>Prerequisites</h3><p>To follow along with this tutorial, you’ll need to have Go installed on your machine, a web browser to view the app, and a command line to execute build commands.</p><p><strong>Go,</strong> or as its normally called <strong>Golang</strong>, is a programming language developed by Google for building modern software. Go is a language designed to get stuff done efficiently and quickly. The key benefits of Go include:</p><ul><li>Strongly typed and garbage collected</li><li>Blazing fast compile times</li><li>Concurrency built in</li><li>Extensive standard library</li></ul><p>Head over to the <a href="https://golang.org/dl/">downloads section</a> of the Go website to get Go running on your machine.</p><h3>Building an app with Gin</h3><p>We’ll be building a simple joke listing app with <strong>Gin</strong>. Our app will list some silly dad jokes. We are going to add authentication to it, so that all logged-in users will have the privilege to like and view jokes.</p><p>This will allow us illustrate how <strong>Gin</strong> can be used to develop web applications and/or APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*65w7hgQ59f1vDwJE.png" /></figure><p>We’ll be making use of the following functionalities offered by Gin:</p><ul><li>Middleware</li><li>Routing</li><li>Routes Grouping</li></ul><h3>Ready, set, Go</h3><p>We will write our entire Go application in a main.go file. Since it’s a small application, it’s going to be easy to build the application with just go run from the terminal.</p><p>We’ll create a new directory golang-gin in our Go workspace, and then a main.go file in it:</p><pre>$ mkdir -p $GOPATH/src/github.com/user/golang-gin<br>$ cd $GOPATH/src/github.com/user/golang-gin<br>$ touch main.go</pre><p>The content of the main.go file:</p><pre>package main</pre><pre>import (<br>  &quot;net/http&quot;</pre><pre>  &quot;github.com/gin-gonic/contrib/static&quot;<br>  &quot;github.com/gin-gonic/gin&quot;<br>)</pre><pre>func main() {<br>  // Set the router as the default one shipped with Gin<br>  router := gin.Default()</pre><pre>  // Serve frontend static files<br>  router.Use(static.Serve(&quot;/&quot;, static.LocalFile(&quot;./views&quot;, true)))</pre><pre>  // Setup route group for the API<br>  api := router.Group(&quot;/api&quot;)<br>  {<br>    api.GET(&quot;/&quot;, func(c *gin.Context) {<br>      c.JSON(http.StatusOK, gin.H {<br>        &quot;message&quot;: &quot;pong&quot;,<br>      })<br>    })<br>  }</pre><pre>  // Start and run the server<br>  router.Run(&quot;:3000&quot;)<br>}</pre><p>We’ll need to create some more directories for our static files. In the same directory as the main.go file, let&#39;s create a views folder. In the views folder, create a js folder and an index.html file in it.</p><p>The index.html file will be very simple for now:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;Jokeish App&lt;/title&gt;<br>&lt;/head&gt;</pre><pre>&lt;body&gt;<br>  &lt;h1&gt;Welcome to the Jokeish App&lt;/h1&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Before we test what we have so far, let’s install the added dependencies:</p><pre>$ go get -u github.com/gin-gonic/gin<br>$ go get -u github.com/gin-gonic/contrib/static</pre><p>To see what’s working, we’ll need to start our server by running go run main.go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/0*dreiayD978SE-CRj.png" /></figure><p>Once the application is running, navigate to http://localhost:3000 in your browser. If all went well, you should see level 1 header text <strong>Welcome to the Jokeish App</strong> displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*H0E9rYj6LZyeK8js.png" /></figure><h3>Defining the API</h3><p>Let’s add some more code in our main.go file for our API definitions. We&#39;ll update our main function with two routes /jokes/ and /jokes/like/:jokeID to the route group /api/.</p><pre>func main() {<br>  // ... leave the code above untouched...</pre><pre>  // Our API will consit of just two routes<br>  // /jokes - which will retrieve a list of jokes a user can see<br>  // /jokes/like/:jokeID - which will capture likes sent to a particular joke<br>  api.GET(&quot;/jokes&quot;, JokeHandler)<br>  api.POST(&quot;/jokes/like/:jokeID&quot;, LikeJoke)<br>}</pre><pre>// JokeHandler retrieves a list of available jokes<br>func JokeHandler(c *gin.Context) {<br>  c.Header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  c.JSON(http.StatusOK, gin.H {<br>    &quot;message&quot;:&quot;Jokes handler not implemented yet&quot;,<br>  })<br>}</pre><pre>// LikeJoke increments the likes of a particular joke Item<br>func LikeJoke(c *gin.Context) {<br>  c.Header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  c.JSON(http.StatusOK, gin.H {<br>    &quot;message&quot;:&quot;LikeJoke handler not implemented yet&quot;,<br>  })<br>}</pre><p>The content of the main.go file should look like this:</p><pre>package main</pre><pre>import (<br>  &quot;net/http&quot;</pre><pre>  &quot;github.com/gin-gonic/contrib/static&quot;<br>  &quot;github.com/gin-gonic/gin&quot;<br>)</pre><pre>func main() {<br>  // Set the router as the default one shipped with Gin<br>  router := gin.Default()</pre><pre>  // Serve frontend static files<br>  router.Use(static.Serve(&quot;/&quot;, static.LocalFile(&quot;./views&quot;, true)))</pre><pre>  // Setup route group for the API<br>  api := router.Group(&quot;/api&quot;)<br>  {<br>    api.GET(&quot;/&quot;, func(c *gin.Context) {<br>      c.JSON(http.StatusOK, gin.H {<br>        &quot;message&quot;: &quot;pong&quot;,<br>      })<br>    })<br>  }<br>  // Our API will consit of just two routes<br>  // /jokes - which will retrieve a list of jokes a user can see<br>  // /jokes/like/:jokeID - which will capture likes sent to a particular joke<br>  api.GET(&quot;/jokes&quot;, JokeHandler)<br>  api.POST(&quot;/jokes/like/:jokeID&quot;, LikeJoke)</pre><pre>  // Start and run the server<br>  router.Run(&quot;:3000&quot;)<br>}</pre><pre>// JokeHandler retrieves a list of available jokes<br>func JokeHandler(c *gin.Context) {<br>  c.Header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  c.JSON(http.StatusOK, gin.H {<br>    &quot;message&quot;:&quot;Jokes handler not implemented yet&quot;,<br>  })<br>}</pre><pre>// LikeJoke increments the likes of a particular joke Item<br>func LikeJoke(c *gin.Context) {<br>  c.Header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  c.JSON(http.StatusOK, gin.H {<br>    &quot;message&quot;:&quot;LikeJoke handler not implemented yet&quot;,<br>  })<br>}</pre><p>Let’s run our app again go run main.go, and access our routes. http://localhost:3000/api/jokes will return a 200 OK header response, with the message jokes handler not implemented yet. A POST request to http://localhost:3000/api/jokes/like/1 returns a 200 OK header, and the message Likejoke handler not implemented yet.</p><h3>Jokes data</h3><p>Since we already have our routes definition set, which does only one thing (return a JSON response), we’ll spice up our codebase a bit by adding some more code to it.</p><pre>// ... leave the code above untouched...</pre><pre>// Let&#39;s create our Jokes struct. This will contain information about a Joke</pre><pre>// Joke contains information about a single Joke<br>type Joke struct {<br>  ID     int     `json:&quot;id&quot; binding:&quot;required&quot;`<br>  Likes  int     `json:&quot;likes&quot;`<br>  Joke   string  `json:&quot;joke&quot; binding:&quot;required&quot;`<br>}</pre><pre>// We&#39;ll create a list of jokes<br>var jokes = []Joke{<br>  Joke{1, 0, &quot;Did you hear about the restaurant on the moon? Great food, no atmosphere.&quot;},<br>  Joke{2, 0, &quot;What do you call a fake noodle? An Impasta.&quot;},<br>  Joke{3, 0, &quot;How many apples grow on a tree? All of them.&quot;},<br>  Joke{4, 0, &quot;Want to hear a joke about paper? Nevermind it&#39;s tearable.&quot;},<br>  Joke{5, 0, &quot;I just watched a program about beavers. It was the best dam program I&#39;ve ever seen.&quot;},<br>  Joke{6, 0, &quot;Why did the coffee file a police report? It got mugged.&quot;},<br>  Joke{7, 0, &quot;How does a penguin build it&#39;s house? Igloos it together.&quot;},<br>}</pre><pre>func main() {<br>  // ... leave this block untouched...<br>}</pre><pre>// JokeHandler retrieves a list of available jokes<br>func JokeHandler(c *gin.Context) {<br>  c.Header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  c.JSON(http.StatusOK, jokes)<br>}</pre><pre>// LikeJoke increments the likes of a particular joke Item<br>func LikeJoke(c *gin.Context) {<br>  // confirm Joke ID sent is valid<br>  // remember to import the `strconv` package<br>  if jokeid, err := strconv.Atoi(c.Param(&quot;jokeID&quot;)); err == nil {<br>    // find joke, and increment likes<br>    for i := 0; i &lt; len(jokes); i++ {<br>      if jokes[i].ID == jokeid {<br>        jokes[i].Likes += 1<br>      }<br>    }</pre><pre>    // return a pointer to the updated jokes list<br>    c.JSON(http.StatusOK, &amp;jokes)<br>  } else {<br>    // Joke ID is invalid<br>    c.AbortWithStatus(http.StatusNotFound)<br>  }<br>}</pre><pre>// NB: Replace the JokeHandler and LikeJoke functions in the previous version to the ones above</pre><p>With our code looking good, let’s go ahead and test our API. We can test with cURL or postman , and then send a GET request to http://localhost:3000/jokes to get the full list of jokes, and a POST request to http://localhost:3000/jokes/like/{jokeid} to increment the likes of a joke.</p><pre>$ curl http://localhost:3000/api/jokes</pre><pre>$ curl -X POST <a href="http://localhost:3000/api/jokes/like/4">http://localhost:3000/api/jokes/like/4</a></pre><h3>Building the UI (React)</h3><p>We have our API in place, so let’s build a frontend to present the data from our API. For this, we’ll be using React. We won’t go too deep into React, as it will be out of the scope of this tutorial. If you need to learn more about React, checkout the official <a href="https://facebook.github.io/react/docs/tutorial.html">tutorial</a>. You can implement the UI with any frontend framework you’re comfortable with.</p><h3>Setup</h3><p>We’ll edit the index.html file to add the external libraries needed to run React. Then we&#39;ll need to create an app.jsx file in the views/js directory, which will contain our React code.</p><p>Our index.html file should look like this:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;</pre><pre>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no&quot; /&gt;<br>  &lt;title&gt;Jokeish App&lt;/title&gt;<br>  &lt;script src=&quot;http://code.jquery.com/jquery-2.1.4.min.js&quot;&gt;&lt;/script&gt;<br>  &lt;script src=&quot;https://cdn.auth0.com/js/auth0/9.0/auth0.min.js&quot;&gt;&lt;/script&gt;<br>  &lt;script type=&quot;application/javascript&quot; src=&quot;https://unpkg.com/react@16.0.0/umd/react.production.min.js&quot;&gt;&lt;/script&gt;<br>  &lt;script type=&quot;application/javascript&quot; src=&quot;https://unpkg.com/react-dom@16.0.0/umd/react-dom.production.min.js&quot;&gt;&lt;/script&gt;<br>  &lt;script type=&quot;application/javascript&quot; src=&quot;https://unpkg.com/babel-standalone@6.26.0/babel.js&quot;&gt;&lt;/script&gt;<br>  &lt;script type=&quot;text/babel&quot; src=&quot;js/app.jsx&quot;&gt;&lt;/script&gt;<br>  &lt;link href=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;&gt;<br>&lt;/head&gt;</pre><pre>&lt;body&gt;<br>  &lt;div id=&quot;app&quot;&gt;&lt;/div&gt;<br>&lt;/body&gt;</pre><pre>&lt;/html&gt;</pre><h3>Building our components</h3><p>In React, views are broken down into components. We’ll need to build some components:</p><ul><li>an App component as the main entry that launches the application</li><li>a Home component which will face non logged-in users</li><li>a LoggedIn component with content only visible by authenticated users</li><li>and a Joke component to display a list of jokes.</li></ul><p>We&#39;ll write all these components in the app.jsx file.</p><h3>The app component</h3><p>This component bootstraps our entire React app. It decides which component to show based on whether a user is authenticated or not. We’ll start off with just its base, and later update it with more functionality.</p><pre>class App extends React.Component {<br>  render() {<br>    if (this.loggedIn) {<br>      return (&lt;LoggedIn /&gt;);<br>    } else {<br>      return (&lt;Home /&gt;);<br>    }<br>  }<br>}</pre><h3>The Home component</h3><p>This component is shown to non logged-in users, along with a button which opens a Hosted lock screen where they can signup or login. We’ll add this functionality later.</p><pre>class Home extends React.Component {<br>  render() {<br>    return (<br>      &lt;div className=&quot;container&quot;&gt;<br>        &lt;div className=&quot;col-xs-8 col-xs-offset-2 jumbotron text-center&quot;&gt;<br>          &lt;h1&gt;Jokeish&lt;/h1&gt;<br>          &lt;p&gt;A load of Dad jokes XD&lt;/p&gt;<br>          &lt;p&gt;Sign in to get access &lt;/p&gt;<br>          &lt;a onClick={this.authenticate} className=&quot;btn btn-primary btn-lg btn-login btn-block&quot;&gt;Sign In&lt;/a&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><h3>LoggedIn component</h3><p>This component is displayed when a user is authenticated. It stores in its state an array of jokes which is populated when the component mounts.</p><pre>class LoggedIn extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      jokes: []<br>    }<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;div className=&quot;container&quot;&gt;<br>        &lt;div className=&quot;col-lg-12&quot;&gt;<br>          &lt;br /&gt;<br>          &lt;span className=&quot;pull-right&quot;&gt;&lt;a onClick={this.logout}&gt;Log out&lt;/a&gt;&lt;/span&gt;<br>          &lt;h2&gt;Jokeish&lt;/h2&gt;<br>          &lt;p&gt;Let&#39;s feed you with some funny Jokes!!!&lt;/p&gt;<br>          &lt;div className=&quot;row&quot;&gt;<br>            {this.state.jokes.map(function(joke, i){<br>              return (&lt;Joke key={i} joke={joke} /&gt;);<br>            })}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><h3>The Joke component</h3><p>The Joke component will contain information about each item from the jokes response to be displayed.</p><pre>class Joke extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      liked: &quot;&quot;<br>    }<br>    this.like = this.like.bind(this);<br>  }</pre><pre>  like() {<br>    // ... we&#39;ll add this block later<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;div className=&quot;col-xs-4&quot;&gt;<br>        &lt;div className=&quot;panel panel-default&quot;&gt;<br>          &lt;div className=&quot;panel-heading&quot;&gt;#{this.props.joke.id} &lt;span className=&quot;pull-right&quot;&gt;{this.state.liked}&lt;/span&gt;&lt;/div&gt;<br>          &lt;div className=&quot;panel-body&quot;&gt;<br>            {this.props.joke.joke}<br>          &lt;/div&gt;<br>          &lt;div className=&quot;panel-footer&quot;&gt;<br>            {this.props.joke.likes} Likes &amp;nbsp;<br>            &lt;a onClick={this.like} className=&quot;btn btn-default&quot;&gt;<br>              &lt;span className=&quot;glyphicon glyphicon-thumbs-up&quot;&gt;&lt;/span&gt;<br>            &lt;/a&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><p>We’ve written our components, so now let’s tell React where to render the app. We’ll add the block of code below to the bottom of our app.jsx file.</p><pre>ReactDOM.render(&lt;App /&gt;, document.getElementById(&#39;app&#39;));</pre><p>Let’s restart our Go server go run main.go, and head over to our app&#39;s URL http://localhost:3000/. You&#39;ll see that the Home component is being rendered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*YTH0oTdqFJuXmKVO.png" /></figure><h3>Securing our jokes app with Auth0</h3><p><strong>Auth0</strong> issues <a href="https://jwt.io/">JSON Web Tokens</a> on every login for your users. This means that you can have a solid <a href="https://auth0.com/docs/identityproviders">identity infrastructure</a>, including <a href="https://auth0.com/docs/sso/single-sign-on">single sign-on</a>, user management, support for social identity providers (Facebook, Github, Twitter, etc.), enterprise identity providers (Active Directory, LDAP, SAML, etc.) and your own database of users, with just a few lines of code.</p><p>We can easily set up authentication in our GIN app by using Auth0. You’ll need an account to follow along with this part. If you don’t already have an Auth0 account, <a href="https://auth0.com/signup">sign up</a> for one now.</p><blockquote><em>Disclaimer: This isn’t sponsored content.</em></blockquote><h3>Creating the API client</h3><p>Our tokens will be generated with Auth0, so we need to create an API and a Client from our Auth0 dashboard. Again, if you haven’t already, <a href="https://auth0.com/signup">sign up</a> for an Auth0 account.</p><p>To create a new API, navigate to the <a href="https://manage.auth0.com/#/apis">APIs section</a> in your dashboard, and click the <strong>Create API</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*2G-e4AZwRWJ4DJ3Z.png" /></figure><p>Choose an API <strong>name</strong> and an <strong>identifier</strong>. The identifier will be the <strong>audience</strong> for the middleware. The <strong>Signing Algorithm</strong> should be <strong>RS256</strong>.</p><p>To create a new Client, navigate to the <a href="https://dev.to/codehakase/building-a-web-app-with-go-gin-and-react-5ke">clients section</a> in your dashboard, and click the <strong>Create Client</strong> button. Select the type Regular Web Applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*4PMmHqHYgiH1mc_p.png" /></figure><p>Once the client is created, take note of the client_id and client_secret, as we&#39;ll need them later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*XTleE3Xxh3_mya-X.png" /></figure><p>We have to add the credentials needed for our API to an environment variable. In the root directory, create a new file .env and add the following to it, with the details from the Auth0 dashboard:</p><pre>export AUTH0_API_CLIENT_SECRET=&quot;&quot;<br>export AUTH0_CLIENT_ID=&quot;&quot;<br>export AUTH0_DOMAIN=&quot;yourdomain.auth0.com&quot;<br>export AUTH0_API_AUDIENCE=&quot;&quot;</pre><h3>Securing our API endpoints</h3><p>Currently, our API is open to the world. We need to secure our endpoints, so only authorized users can access them.</p><p>We are going to make use of a <strong>JWT Middleware</strong> to check for a valid <strong>JSON Web Token</strong> from each request hitting our endpoints.</p><p>Let’s create our middleware:</p><pre>// ...</pre><pre>var jwtMiddleWare *jwtmiddleware.JWTMiddleware</pre><pre>func main() {<br>  jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{<br>    ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {<br>      aud := os.Getenv(&quot;AUTH0_API_AUDIENCE&quot;)<br>      checkAudience := token.Claims.(jwt.MapClaims).VerifyAudience(aud, false)<br>      if !checkAudience {<br>        return token, errors.New(&quot;Invalid audience.&quot;)<br>      }<br>      // verify iss claim<br>      iss := os.Getenv(&quot;AUTH0_DOMAIN&quot;)<br>      checkIss := token.Claims.(jwt.MapClaims).VerifyIssuer(iss, false)<br>      if !checkIss {<br>        return token, errors.New(&quot;Invalid issuer.&quot;)<br>      }</pre><pre>      cert, err := getPemCert(token)<br>      if err != nil {<br>        log.Fatalf(&quot;could not get cert: %+v&quot;, err)<br>      }</pre><pre>      result, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(cert))<br>      return result, nil<br>    },<br>    SigningMethod: jwt.SigningMethodRS256,<br>  })</pre><pre>  // register our actual jwtMiddleware<br>  jwtMiddleWare = jwtMiddleware</pre><pre>  // ... the rest of the code below this function doesn&#39;t change yet<br>}</pre><pre>// authMiddleware intercepts the requests, and check for a valid jwt token<br>func authMiddleware() gin.HandlerFunc {<br>  return func(c *gin.Context) {<br>    // Get the client secret key<br>    err := jwtMiddleWare.CheckJWT(c.Writer, c.Request)<br>    if err != nil {<br>      // Token not found<br>      fmt.Println(err)<br>      c.Abort()<br>      c.Writer.WriteHeader(http.StatusUnauthorized)<br>      c.Writer.Write([]byte(&quot;Unauthorized&quot;))<br>      return<br>    }<br>  }<br>}</pre><p>In the above code, we have a new jwtMiddleWare variable which is initialized in the main function. It is used in the authMiddleware middle function.</p><p>If you notice, we are pulling our server-side credentials from an environment variable (one of the tenets of a <strong>12-factor app</strong>). Our middleware checks and receives a token from a request and calls the jwtMiddleWare.CheckJWT method to validate the token sent.</p><p>Let’s also write the function to return the JSON Web Keys:</p><pre>// ... the code above is untouched...</pre><pre>// Jwks stores a slice of JSON Web Keys<br>type Jwks struct {<br>  Keys []JSONWebKeys `json:&quot;keys&quot;`<br>}</pre><pre>type JSONWebKeys struct {<br>  Kty string   `json:&quot;kty&quot;`<br>  Kid string   `json:&quot;kid&quot;`<br>  Use string   `json:&quot;use&quot;`<br>  N   string   `json:&quot;n&quot;`<br>  E   string   `json:&quot;e&quot;`<br>  X5c []string `json:&quot;x5c&quot;`<br>}</pre><pre>func main() {<br>  // ... the code in this method is untouched...<br>}</pre><pre>func getPemCert(token *jwt.Token) (string, error) {<br>  cert := &quot;&quot;<br>  resp, err := http.Get(os.Getenv(&quot;AUTH0_DOMAIN&quot;) + &quot;.well-known/jwks.json&quot;)<br>  if err != nil {<br>    return cert, err<br>  }<br>  defer resp.Body.Close()</pre><pre>  var jwks = Jwks{}<br>  err = json.NewDecoder(resp.Body).Decode(&amp;jwks)</pre><pre>  if err != nil {<br>    return cert, err<br>  }</pre><pre>  x5c := jwks.Keys[0].X5c<br>  for k, v := range x5c {<br>    if token.Header[&quot;kid&quot;] == jwks.Keys[k].Kid {<br>      cert = &quot;-----BEGIN CERTIFICATE-----\n&quot; + v + &quot;\n-----END CERTIFICATE-----&quot;<br>    }<br>  }</pre><pre>  if cert == &quot;&quot; {<br>    return cert, errors.New(&quot;unable to find appropriate key.&quot;)<br>  }</pre><pre>  return cert, nil<br>}</pre><h3>Using the JWT middleware</h3><p>Using the middleware is very straightforward. We just pass it as a parameter to our routes definition.</p><pre>...</pre><pre>api.GET(&quot;/jokes&quot;, authMiddleware(), JokeHandler)<br>api.POST(&quot;/jokes/like/:jokeID&quot;, authMiddleware(), LikeJoke)</pre><pre>...</pre><p>Our main.go file should look like this:</p><pre>package main</pre><pre>import (<br>  &quot;encoding/json&quot;<br>  &quot;errors&quot;<br>  &quot;fmt&quot;<br>  &quot;log&quot;<br>  &quot;net/http&quot;<br>  &quot;os&quot;<br>  &quot;strconv&quot;</pre><pre>  jwtmiddleware &quot;github.com/auth0/go-jwt-middleware&quot;<br>  jwt &quot;github.com/dgrijalva/jwt-go&quot;<br>  &quot;github.com/gin-gonic/contrib/static&quot;<br>  &quot;github.com/gin-gonic/gin&quot;<br>)</pre><pre>type Response struct {<br>  Message string `json:&quot;message&quot;`<br>}</pre><pre>type Jwks struct {<br>  Keys []JSONWebKeys `json:&quot;keys&quot;`<br>}</pre><pre>type JSONWebKeys struct {<br>  Kty string   `json:&quot;kty&quot;`<br>  Kid string   `json:&quot;kid&quot;`<br>  Use string   `json:&quot;use&quot;`<br>  N   string   `json:&quot;n&quot;`<br>  E   string   `json:&quot;e&quot;`<br>  X5c []string `json:&quot;x5c&quot;`<br>}</pre><pre>type Joke struct {<br>  ID    int    `json:&quot;id&quot; binding:&quot;required&quot;`<br>  Likes int    `json:&quot;likes&quot;`<br>  Joke  string `json:&quot;joke&quot; binding:&quot;required&quot;`<br>}</pre><pre>/** we&#39;ll create a list of jokes */<br>var jokes = []Joke{<br>  Joke{1, 0, &quot;Did you hear about the restaurant on the moon? Great food, no atmosphere.&quot;},<br>  Joke{2, 0, &quot;What do you call a fake noodle? An Impasta.&quot;},<br>  Joke{3, 0, &quot;How many apples grow on a tree? All of them.&quot;},<br>  Joke{4, 0, &quot;Want to hear a joke about paper? Nevermind it&#39;s tearable.&quot;},<br>  Joke{5, 0, &quot;I just watched a program about beavers. It was the best dam program I&#39;ve ever seen.&quot;},<br>  Joke{6, 0, &quot;Why did the coffee file a police report? It got mugged.&quot;},<br>  Joke{7, 0, &quot;How does a penguin build it&#39;s house? Igloos it together.&quot;},<br>}</pre><pre>var jwtMiddleWare *jwtmiddleware.JWTMiddleware</pre><pre>func main() {<br>  jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{<br>    ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {<br>      aud := os.Getenv(&quot;AUTH0_API_AUDIENCE&quot;)<br>      checkAudience := token.Claims.(jwt.MapClaims).VerifyAudience(aud, false)<br>      if !checkAudience {<br>        return token, errors.New(&quot;Invalid audience.&quot;)<br>      }<br>      // verify iss claim<br>      iss := os.Getenv(&quot;AUTH0_DOMAIN&quot;)<br>      checkIss := token.Claims.(jwt.MapClaims).VerifyIssuer(iss, false)<br>      if !checkIss {<br>        return token, errors.New(&quot;Invalid issuer.&quot;)<br>      }</pre><pre>      cert, err := getPemCert(token)<br>      if err != nil {<br>        log.Fatalf(&quot;could not get cert: %+v&quot;, err)<br>      }</pre><pre>      result, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(cert))<br>      return result, nil<br>    },<br>    SigningMethod: jwt.SigningMethodRS256,<br>  })</pre><pre>  jwtMiddleWare = jwtMiddleware<br>  // Set the router as the default one shipped with Gin<br>  router := gin.Default()</pre><pre>  // Serve the frontend<br>  router.Use(static.Serve(&quot;/&quot;, static.LocalFile(&quot;./views&quot;, true)))</pre><pre>  api := router.Group(&quot;/api&quot;)<br>  {<br>    api.GET(&quot;/&quot;, func(c *gin.Context) {<br>      c.JSON(http.StatusOK, gin.H{<br>        &quot;message&quot;: &quot;pong&quot;,<br>      })<br>    })<br>    api.GET(&quot;/jokes&quot;, authMiddleware(), JokeHandler)<br>    api.POST(&quot;/jokes/like/:jokeID&quot;, authMiddleware(), LikeJoke)<br>  }<br>  // Start the app<br>  router.Run(&quot;:3000&quot;)<br>}</pre><pre>func getPemCert(token *jwt.Token) (string, error) {<br>  cert := &quot;&quot;<br>  resp, err := http.Get(os.Getenv(&quot;AUTH0_DOMAIN&quot;) + &quot;.well-known/jwks.json&quot;)<br>  if err != nil {<br>    return cert, err<br>  }<br>  defer resp.Body.Close()</pre><pre>  var jwks = Jwks{}<br>  err = json.NewDecoder(resp.Body).Decode(&amp;jwks)</pre><pre>  if err != nil {<br>    return cert, err<br>  }</pre><pre>  x5c := jwks.Keys[0].X5c<br>  for k, v := range x5c {<br>    if token.Header[&quot;kid&quot;] == jwks.Keys[k].Kid {<br>      cert = &quot;-----BEGIN CERTIFICATE-----\n&quot; + v + &quot;\n-----END CERTIFICATE-----&quot;<br>    }<br>  }</pre><pre>  if cert == &quot;&quot; {<br>    return cert, errors.New(&quot;unable to find appropriate key&quot;)<br>  }</pre><pre>  return cert, nil<br>}</pre><pre>// authMiddleware intercepts the requests, and check for a valid jwt token<br>func authMiddleware() gin.HandlerFunc {<br>  return func(c *gin.Context) {<br>    // Get the client secret key<br>    err := jwtMiddleWare.CheckJWT(c.Writer, c.Request)<br>    if err != nil {<br>      // Token not found<br>      fmt.Println(err)<br>      c.Abort()<br>      c.Writer.WriteHeader(http.StatusUnauthorized)<br>      c.Writer.Write([]byte(&quot;Unauthorized&quot;))<br>      return<br>    }<br>  }<br>}</pre><pre>// JokeHandler returns a list of jokes available (in memory)<br>func JokeHandler(c *gin.Context) {<br>  c.Header(&quot;Content-Type&quot;, &quot;application/json&quot;)</pre><pre>  c.JSON(http.StatusOK, jokes)<br>}</pre><pre>func LikeJoke(c *gin.Context) {<br>  // Check joke ID is valid<br>  if jokeid, err := strconv.Atoi(c.Param(&quot;jokeID&quot;)); err == nil {<br>    // find joke and increment likes<br>    for i := 0; i &lt; len(jokes); i++ {<br>      if jokes[i].ID == jokeid {<br>        jokes[i].Likes = jokes[i].Likes + 1<br>      }<br>    }<br>    c.JSON(http.StatusOK, &amp;jokes)<br>  } else {<br>    // the jokes ID is invalid<br>    c.AbortWithStatus(http.StatusNotFound)<br>  }<br>}</pre><p>Let’s install the jwtmiddleware libraries:</p><pre>$ go get -u github.com/auth0/go-jwt-middleware<br>$ go get -u github.com/dgrijalva/jwt-go</pre><p>Let’s source our environment file, and restart our app server:</p><pre>$ source .env<br>$ go run main.go</pre><p>Now if we try accessing any of the endpoints, we’ll be faced with a 401 Unauthorized error. That&#39;s because we need to send along a token with the request.</p><h3>Login with Auth0 and React</h3><p>Let’s implement a login system so that users can login or create accounts and get access to our jokes. We’ll add to our app.jsx file the following Auth0 credentials:</p><ul><li>AUTH0_CLIENT_ID</li><li>AUTH0_DOMAIN</li><li>AUTH0_CALLBACK_URL - The URL of your app</li><li>AUTH0_API_AUDIENCE</li></ul><blockquote><em>You can find the </em><em>AUTH0_CLIENT_ID, </em><em>AUTH0_DOMAIN, and </em><em>AUTH0_API_AUDIENCE data from your Auth0 </em><a href="https://manage.auth0.com/"><em>management dashboard</em></a><em>.</em></blockquote><p>We need to set a callback which Auth0 redirects to. Navigate to the Clients section in your dashboard. In the settings, let&#39;s set the callback to <a href="http://localhost:3000:">http://localhost:3000:</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*e2R2fT3ryBC4eK17.png" /></figure><p>With the credentials in place, let’s update our React components.</p><h4>APP component</h4><pre>const AUTH0_CLIENT_ID = &quot;aIAOt9fkMZKrNsSsFqbKj5KTI0ObTDPP&quot;;<br>const AUTH0_DOMAIN = &quot;hakaselabs.auth0.com&quot;;<br>const AUTH0_CALLBACK_URL = location.href;<br>const AUTH0_API_AUDIENCE = &quot;golang-gin&quot;;</pre><pre>class App extends React.Component {<br>  parseHash() {<br>    this.auth0 = new auth0.WebAuth({<br>      domain: AUTH0_DOMAIN,<br>      clientID: AUTH0_CLIENT_ID<br>    });<br>    this.auth0.parseHash(window.location.hash, (err, authResult) =&gt; {<br>      if (err) {<br>        return console.log(err);<br>      }<br>      if (<br>        authResult !== null &amp;&amp;<br>        authResult.accessToken !== null &amp;&amp;<br>        authResult.idToken !== null<br>      ) {<br>        localStorage.setItem(&quot;access_token&quot;, authResult.accessToken);<br>        localStorage.setItem(&quot;id_token&quot;, authResult.idToken);<br>        localStorage.setItem(<br>          &quot;profile&quot;,<br>          JSON.stringify(authResult.idTokenPayload)<br>        );<br>        window.location = window.location.href.substr(<br>          0,<br>          window.location.href.indexOf(&quot;#&quot;)<br>        );<br>      }<br>    });<br>  }</pre><pre>  setup() {<br>    $.ajaxSetup({<br>      beforeSend: (r) =&gt; {<br>        if (localStorage.getItem(&quot;access_token&quot;)) {<br>          r.setRequestHeader(<br>            &quot;Authorization&quot;,<br>            &quot;Bearer &quot; + localStorage.getItem(&quot;access_token&quot;)<br>          );<br>        }<br>      }<br>    });<br>  }</pre><pre>  setState() {<br>    let idToken = localStorage.getItem(&quot;id_token&quot;);<br>    if (idToken) {<br>      this.loggedIn = true;<br>    } else {<br>      this.loggedIn = false;<br>    }<br>  }</pre><pre>  componentWillMount() {<br>    this.setup();<br>    this.parseHash();<br>    this.setState();<br>  }</pre><pre>  render() {<br>    if (this.loggedIn) {<br>      return &lt;LoggedIn /&gt;;<br>    }<br>    return &lt;Home /&gt;;<br>  }<br>}</pre><p>We updated the App component with three component methods (setup, parseHash, and setState), and a lifecycle method componentWillMount. The parseHash method initializes the auth0 webAuth client and parses the hash to a more readable format, saving them to localSt. To show the lock screen, capture and store the user token and add the correct authorization header to any requests to our API</p><h4>Home component</h4><p>Our Home component will be updated. We’ll add the functionality for the authenticate method, which will trigger the hosted lock screen to display and allow our users to login or signup.</p><pre>class Home extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.authenticate = this.authenticate.bind(this);<br>  }<br>  authenticate() {<br>    this.WebAuth = new auth0.WebAuth({<br>      domain: AUTH0_DOMAIN,<br>      clientID: AUTH0_CLIENT_ID,<br>      scope: &quot;openid profile&quot;,<br>      audience: AUTH0_API_AUDIENCE,<br>      responseType: &quot;token id_token&quot;,<br>      redirectUri: AUTH0_CALLBACK_URL<br>    });<br>    this.WebAuth.authorize();<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;div className=&quot;container&quot;&gt;<br>        &lt;div className=&quot;row&quot;&gt;<br>          &lt;div className=&quot;col-xs-8 col-xs-offset-2 jumbotron text-center&quot;&gt;<br>            &lt;h1&gt;Jokeish&lt;/h1&gt;<br>            &lt;p&gt;A load of Dad jokes XD&lt;/p&gt;<br>            &lt;p&gt;Sign in to get access &lt;/p&gt;<br>            &lt;a<br>              onClick={this.authenticate}<br>              className=&quot;btn btn-primary btn-lg btn-login btn-block&quot;<br>            &gt;<br>              Sign In<br>            &lt;/a&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><h4>LoggedIn component</h4><p>We will update the LoggedIn component to communicate with our API and pull all jokes. It will pass each joke as a prop to the Joke component, which renders a bootstrap panel. Let&#39;s write those:</p><pre>class LoggedIn extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      jokes: []<br>    };</pre><pre>    this.serverRequest = this.serverRequest.bind(this);<br>    this.logout = this.logout.bind(this);<br>  }</pre><pre>  logout() {<br>    localStorage.removeItem(&quot;id_token&quot;);<br>    localStorage.removeItem(&quot;access_token&quot;);<br>    localStorage.removeItem(&quot;profile&quot;);<br>    location.reload();<br>  }</pre><pre>  serverRequest() {<br>    $.get(&quot;http://localhost:3000/api/jokes&quot;, res =&gt; {<br>      this.setState({<br>        jokes: res<br>      });<br>    });<br>  }</pre><pre>  componentDidMount() {<br>    this.serverRequest();<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;div className=&quot;container&quot;&gt;<br>        &lt;br /&gt;<br>        &lt;span className=&quot;pull-right&quot;&gt;<br>          &lt;a onClick={this.logout}&gt;Log out&lt;/a&gt;<br>        &lt;/span&gt;<br>        &lt;h2&gt;Jokeish&lt;/h2&gt;<br>        &lt;p&gt;Let&#39;s feed you with some funny Jokes!!!&lt;/p&gt;<br>        &lt;div className=&quot;row&quot;&gt;<br>          &lt;div className=&quot;container&quot;&gt;<br>            {this.state.jokes.map(function(joke, i) {<br>              return &lt;Joke key={i} joke={joke} /&gt;;<br>            })}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><h4>Joke component</h4><p>We’ll also update the Joke component to format each Joke item passed to it from the Parent compoent (LoggedIn). We’ll also add a like method, which will increment the likes of a Joke.</p><pre>class Joke extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      liked: &quot;&quot;,<br>      jokes: []<br>    };<br>    this.like = this.like.bind(this);<br>    this.serverRequest = this.serverRequest.bind(this);<br>  }</pre><pre>  like() {<br>    let joke = this.props.joke;<br>    this.serverRequest(joke);<br>  }<br>  serverRequest(joke) {<br>    $.post(<br>      &quot;http://localhost:3000/api/jokes/like/&quot; + joke.id,<br>      { like: 1 },<br>      res =&gt; {<br>        console.log(&quot;res... &quot;, res);<br>        this.setState({ liked: &quot;Liked!&quot;, jokes: res });<br>        this.props.jokes = res;<br>      }<br>    );<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;div className=&quot;col-xs-4&quot;&gt;<br>        &lt;div className=&quot;panel panel-default&quot;&gt;<br>          &lt;div className=&quot;panel-heading&quot;&gt;<br>            #{this.props.joke.id}{&quot; &quot;}<br>            &lt;span className=&quot;pull-right&quot;&gt;{this.state.liked}&lt;/span&gt;<br>          &lt;/div&gt;<br>          &lt;div className=&quot;panel-body&quot;&gt;{this.props.joke.joke}&lt;/div&gt;<br>          &lt;div className=&quot;panel-footer&quot;&gt;<br>            {this.props.joke.likes} Likes &amp;nbsp;<br>            &lt;a onClick={this.like} className=&quot;btn btn-default&quot;&gt;<br>              &lt;span className=&quot;glyphicon glyphicon-thumbs-up&quot; /&gt;<br>            &lt;/a&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><h3>Putting it all together</h3><p>With the UI and API complete, we can test our app. We’ll start off by booting our server source .env &amp;&amp; go run main.go, and then we’ll navigate to http://localhost:3000 from any browser. You should see the Home component with a signin button. Clicking on the signin button will redirect to a hosted Lock page (create an account or login) to continue using the application.</p><p><strong>Home:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*hRNvmy9IadBGFujq.png" /></figure><p><strong>Auth0 Hosted Lock Screen:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*A69ePO9y3DI7h7D0.png" /></figure><p><strong>LoggedIn App view:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*88ZMaE5gYfhEiSv_.png" /></figure><h3>Conclusion</h3><p>Congrats! You have learned how to build an application and an API with Go and the Gin framework.</p><p>Did I miss something important? Let me know of it in the comments.</p><p>You can say Hi to me on Twitter <a href="https://twitter.com/codehakase">@codehakase</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cffdc473576" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-to-build-a-web-app-with-go-gin-and-react-cffdc473576">How to build a web app with Go, Gin, and React</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advice From A 20 Year Old Nigerian Software Developer]]></title>
            <link>https://medium.com/@codehakase/advice-from-a-20-year-old-nigerian-software-developer-1825704e3e06?source=rss-38ef9ca6edc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1825704e3e06</guid>
            <category><![CDATA[inspiration]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[nigeria]]></category>
            <category><![CDATA[work]]></category>
            <dc:creator><![CDATA[Francis Sunday]]></dc:creator>
            <pubDate>Fri, 15 Dec 2017 09:09:42 GMT</pubDate>
            <atom:updated>2018-04-08T11:14:23.007Z</atom:updated>
            <content:encoded><![CDATA[<p>Living on this planet (in this lifetime) for 2 decades now, I’ve come to learn a lot of good (and bad) things from everyone and everything around me, I’ve done stuff people my age dare not to (talking about good vibes here…). Some people identify with me as a nerd, one who just looks at screens everyday — maybe he doesn’t have a life, but I don’t think they get what I really do, even when I try so, so hard to explain it. I’ll share what I actually do on a normal day, and what I’ve done so far in order to be a software developer.</p><blockquote>If you’re new to programming, you should grab one or two important points from this article.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-Y0OAruv_4-STNG3V022g.jpeg" /><figcaption>Yeah, I’m a self-acclaimed Sticker Ambassador!</figcaption></figure><h3>Let’s talk about me, and how I got started with coding</h3><p>I’m Francis, a 20-year-old guy living in Port Harcourt, Nigeria, and I’m a software developer today. I’m growing a strong following online, trying my best to motivate someone out there through the content I share.</p><p>In my country Nigeria, the tech community came to its peck way back in 2014. I wrote my first line of code when I was 17 years old. I built a semi-tech blog where I was dabbling HTML and CSS, and a little bit of JavaScript, the blog got a good following, but I wasn’t serious with it, and its long dead. My progress I’d say wasn’t at a fast pace. I didn’t really have friends who code, neither did I have someone I looked up to (my bad), I didn’t really know much about developer communities around me even when there was. I told my parents about the new skill I was developing, they didn’t even understand jack out of it LOL. I kept on building stuff and yeah I felt like Zeus the Greek god and most the times, a total jerk. Then I had no idea that this stuff was something I could make a living off. I got my first client about a year after. It was a website design gig for a health firm. I didn’t really know much about charging clients but the pay I got from my first gig, was what I could earn in 7 months from the job I was doing — it was time to get serious.</p><p>Talk about education, <em>I finished high school when I was 18, and to this moment, ehm.. I’m still contemplating on going to a university (Nigerian) </em>— <strong><em>this may change in future</em></strong>. This is scary I know most especially in my country where almost all sectors look at educational certifications and credentials before one’s skills. I spent so much time trying to get the best grades in high school to hopefully land in an awesome university. Wrote and re-wrote silly examinations poorly regulated, in turn wasting years of my life. I still don’t regret these though — <em>everything happens for a reason, either good or bad</em>.</p><h4>No work experience I think I’m doomed!</h4><p>I became really serious about programming when I was around 18, I put 100% of my time and energy to programming. I literally scrapped the web with the thirst for knowledge. I was doing all these on a low key while trying to know more stuff, I forgot I needed something to show to an employer or recruiter if asked. I had built so many stuff, some of them silly (but nothing is too silly). I learned Version control with Git and Github and hosted some of my code online.</p><p>I had a hard time with non-technical clients. Yeah, they don’t know what you mean when you say you can build a REST API with JavaScript, or you can spin off and EC2 instance easily with one command, they just want to see what you’ve done in the past. That I didn’t really have. I was too ashamed to show them clients file upload scripts I worked on in PHP, or a JavaScript-powered calculator, it didn’t fit in. I hacked my way around with the help of referrals and <em>big talks</em>. I was able to build up a clientèle and yeah the pay was cool, my parents were impressed at the amount of money I was earning, I could swear they had gone to pray in church severally thinking I was a scammer LOL.</p><blockquote>You may not really learn to code at school, you’ll learn by building stuff. Most companies don’t care if you have a CS degree, they want to know how good your coding skills are.</blockquote><h4>Building a personal brand</h4><p>I’ve been able to build (still building) up my software development skillset over the years, I can build products with several languages such as, JavaScript (with the MERN stack), PHP (with Laravel), HTML/CSS, and Go (I love this baby), and I also use awesome power tools for my workflow. I take my social media accounts really seriously. When my online following was growing, I had to go back to my various social accounts to delete some silly stuff I had posted when I was younger, I don’t want any recruiting agency seeing silly content, that may be a big red flag.</p><p>I write technical articles on my <a href="https://hakaselabs.github.io/">BLOG</a> and on other online publications like <a href="https://dev.to/codehakase">The Practical Dev</a>. I’ve designed (and redesigned) my <a href="https://codehakase.ninja/">personal website</a> myself to showcase some of my latest works (I can legally show). I mentor and offer freelance services on <a href="https://codementor.io/codehakase">Codementor</a>. I really try not to stay idle, I make use of social media to spread the word about the tech community, awesome tools I use or discovered, food, and myself too. I rant on twitter <a href="https://twitter.com/codehakase">@codehakase,</a> and inspire with images on Instagram <a href="https://instagram.com/codehakase">@codehakase</a>.</p><h4>Community matters</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ubJsWLQZQc-rAqTBzshx9Q.jpeg" /><figcaption>a shot by techpoint — forLoopAfrica meetup Lagos 2017</figcaption></figure><p>One awesome thing about coding, is the massive amount of people in various communities doing awesome things to push the word about tech to the ends of the earth. These communities have been a major part of most successful techies today. Some of these communities are Google Developer Groups, <a href="http://forloop.africa/">ForLoop Africa,</a> Microsoft Developers Network, Frontstack, etc.</p><p>I’ve contributed in my own way to the Nigerian tech communities, I co-organized the maiden meetup for the Port Harcourt chapter for ForLoop Africa, I co-lead a local developer community in Port Harcourt — <strong><em>PHDevConnect</em></strong>. I’ve facilitated, volunteered for other local communities and tech events in Nigeria. It’s so amazing how I’m able to be part of movements inspiring people to indulge in tech. My experience so far has been spectacular.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fA0PBWvF_EaGtAAAnestIw.jpeg" /><figcaption>You see, no screens around, just me (with the silly smile), Rico, and his pal</figcaption></figure><h3>Outside Work, My Daily life</h3><p>I’m quite a busy person even outside programming, I don’t really stay idle. So what do I do on a regular day?</p><p>I try to take a walk. I spend most of my time sitting, taking a walk reliefs me off stress, and gets my brain in a good shape. I’m a music fanatic too, I play the violin and the piano. I secretly compose pieces for the piano and other orchestral instruments (unfortunately I haven’t finished any to publish yet).</p><p>I also do some other stuff like trading cryptocurrencies, Forex, and a little Day trading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hEbJvltnslRrdEzjWQ7Img.jpeg" /></figure><p>I devote some time to working on my personal projects. They help broaden my technical skills. I sometimes build stuff with new technologies I haven’t tried before to get the experience. Most times, things don’t go as planned yikes! But hey I’m super cool at <strong>googling stuff.</strong> I sometimes figure out things and yes I feel happy because I could do it again and again, its now stuck in memory.</p><p>I do some CS stuff. Though I don’t have a formal computer science background, I try my best to get to know the CS fundamentals. I’m taking <strong>Harvard’s CS50</strong> and yeah the content of that course is super awesome. I also go to YouTube to checkout interesting videos on programming, and computer science, and algorithms.</p><p>I try to keep up with the software development community. I read up articles on tech blogs, to learn something new, like a new feature from the languages I develop in, or the new tech that’s out.</p><p><strong>I try out new eating spots. </strong>Eating is what I can’t do without. I’m a foodie (a nutritious one), I try out new cuisines from new or my favourite spots. I like to spoil myself to a good meal once in a while (actually once a week lol) sometimes with friends or just me. One has to be healthy to be super productive during work.</p><p>I sometimes go parting (<em>hope my parents aren’t reading this…</em>) on Friday nights, to shake off work stress, though I’m not into alcohol and smoking, I just stick to softs — health is important here people.</p><h3>Conclusion</h3><p>While writing this article, I had to reflect deep, and took a deep drive into memory lane. I remember some time ago when I was around 12 or thereabout, I loved science fiction movies a lot. I always wanted to become a mad scientist LOL. Then I’d also see hackers and programmers in movies being portrayed as super intelligent humans,. Oh boy, I got pretty scared while I got older, I never thought I’d be a developer today, I wasn’t super cool with math (you don’t really need much maths to program). <strong>Programming, in general, is for everyone. If you love to create stuff try it, its not hard as people make it seem like.</strong></p><p>If you haven’t seen any useful tip or point to take home with from this text of mine, don’t forget any of these:</p><ul><li>Programming is not designed for a specific group of smart persons, absolutely anyone can write good computer programs. I know people who’ve switched to programming from a totally different career line.</li><li>While taking the bold step to choosing this field, you should know its normal to feel awkward and uncomfortable most times, don’t let those weigh you down, they should push you to do more rather.</li><li>While in your quest to being a world class software engineer, as a steady booster, look back and see how far you’ve come, how much you’ve improved from the previous day, week or year, you’d be super motivated to continue.</li><li>Join online communities, attend meetups, network with others like you, it helps a lot, you’d find someone to share your story with</li></ul><p>I really enjoyed writing this piece, I hope you enjoyed reading? Did I miss something important? Feel free to leave a comment below.</p><p>You can connect with me on <a href="https://twitter.com/codehakase">Twitter</a> | <a href="https://fb.com/codehakase">Facebook</a> | <a href="https://instagram.com/codehakase">Instagram</a> | <a href="https://linkedin.com/in/codehakase">Linkedin</a></p><p>Cheers!</p><blockquote>This piece was inspired by <a href="https://medium.com/@lydiahallie?source=post_header_lockup">Lydia Hallie</a>’s <a href="https://medium.com/@lydiahallie/advice-from-a-19-y-o-girl-software-developer-88737bcc6be5">article</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1825704e3e06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terminal for Beginners (excepts)]]></title>
            <link>https://medium.com/ph-devconnect/terminal-for-beginners-excepts-bf88a743b2ad?source=rss-38ef9ca6edc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf88a743b2ad</guid>
            <category><![CDATA[getting-started]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[setup]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[terminal]]></category>
            <dc:creator><![CDATA[Francis Sunday]]></dc:creator>
            <pubDate>Sat, 28 Oct 2017 21:26:39 GMT</pubDate>
            <atom:updated>2017-10-28T21:26:39.931Z</atom:updated>
            <content:encoded><![CDATA[<p>Getting into Software Development seem overwhelming (actually it is) these days. One has to go through the hassle of getting familiar with different languages, to organizing codebases, to libraries, frameworks, the list goes on. Every Job description (at least the sane ones), requires additional skills to get the job. Example of such, Version Control (Git or Mecurial), tasks runners, build tools, package managers, etc.</p><p>In this article on my <a href="https://hakaselabs.github.io/2017-10-28/terminal-for-beginers">Blog</a> I introduced the terminal for anyone who’s trying to wrap their heads around the terminal.</p><p>Aricle -&gt; <a href="https://hakaselabs.github.io/2017-10-28/terminal-for-beginers">https://hakaselabs.github.io/2017-10-28/terminal-for-beginers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf88a743b2ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ph-devconnect/terminal-for-beginners-excepts-bf88a743b2ad">Terminal for Beginners (excepts)</a> was originally published in <a href="https://medium.com/ph-devconnect">PH DevConnect</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[New Dev Article on our Publication :)]]></title>
            <link>https://medium.com/ph-devconnect/new-dev-article-on-our-publication-a21f5b645b47?source=rss-38ef9ca6edc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a21f5b645b47</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[phdevconnect]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Francis Sunday]]></dc:creator>
            <pubDate>Tue, 18 Jul 2017 17:30:10 GMT</pubDate>
            <atom:updated>2017-07-18T17:30:10.537Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey! its been a while we’ve seen you read our stories, we just published one <strong>“Building a RESTful API with Go”</strong> Check it out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a21f5b645b47" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ph-devconnect/new-dev-article-on-our-publication-a21f5b645b47">New Dev Article on our Publication :)</a> was originally published in <a href="https://medium.com/ph-devconnect">PH DevConnect</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a RESTful API with Go]]></title>
            <link>https://medium.com/ph-devconnect/building-a-restful-api-with-go-5d5d801ddf02?source=rss-38ef9ca6edc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d5d801ddf02</guid>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Francis Sunday]]></dc:creator>
            <pubDate>Tue, 18 Jul 2017 17:23:44 GMT</pubDate>
            <atom:updated>2017-07-18T17:23:44.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wVfQIu_s4g3OYWhvygwhWQ.png" /><figcaption>Hey my Golang looks good right?</figcaption></figure><p><strong>Go</strong> is an open source programming language that makes it easy to build simple, reliable, and efficient software. Go was created at Google in 2007 by Robert Grisemer, Rob Pike and Ken Thompson. Go is a compiled, statically typed language.</p><blockquote><em>PS: This article is not an introduction to the Go programming language, its an intermediate one.</em></blockquote><p>For the purpose of this tutorial, we’ll be creating a RESTful API for a Phone Book app.</p><h3>REST, RESTful, WTH!!</h3><p><strong>REST</strong> is an acronym for Representational State Transfer. It is a web standards architecture and HTTP Protocol. The REST protocol, decribes six (6) constraints:</p><ol><li>Uniform Interface</li><li>Cacheable</li><li>Client-Server</li><li>Stateless</li><li>Code on Demand</li><li>Layered System</li></ol><p>REST is composed of methods such as a base URL, media types, etc. RESTful applicaitons uses HTTP requests to perform the CRUD operations.</p><h3>Setup</h3><p>To start up writing our API, we need to setup our environment. Get the Latest Release of Go (as of this writing, its <em>1.8.3</em> ) &gt; <a href="https://golang.org/">here</a>. Once you’ve installed Go, you should have a $GOPATH sys variable set. We need a Project directory to store our source, we make one:</p><pre>$ mkdir -p $GOPATH/src/github/{your username}/rest-api</pre><p>The command, will create a rest-api project folder in your Go home.</p><pre>$ cd rest-api</pre><p>Next we create a main.go file</p><h3>Router</h3><p>We’ll need to use a mux to route requests, so we need a Go package for that (<strong>mux</strong> stands for <em>HTTP request multiplexer</em> which matches an incoming request to against a list of routes (registered)). In the rest-api directory, lets require the dependency (package rather).</p><pre>rest-api$ go get github.com/gorilla/mux</pre><p>We set up our main.go file</p><pre>package main</pre><pre>import (<br>    &quot;encoding/json&quot;<br>    &quot;log&quot;<br>    &quot;net/http&quot;<br>    &quot;github.com/gorilla/mux&quot;<br>)</pre><pre>// our main function<br>func main() {<br>    router := mux.NewRouter()<br>    log.Fatal(http.ListenAndServe(&quot;:8000&quot;, router))<br>}</pre><p>If you run this file, it doesn’t really respond to any , so we need to write our Endpoints. For the phonebook api, we’d need these s:</p><ul><li>/people (GET) -&gt; All persons in the phonebook document (database)</li><li>/people/{id} (GET) -&gt; Get a single person</li><li>/people/{id} (POST) -&gt; Create a new person</li><li>/people/{id} (DELETE) -&gt; Delete a person</li></ul><p>We should write the routes handle for those s, and their methods too</p><pre>// fun main()<br>func main() {<br>    router := mux.NewRouter()<br>    router.HandleFunc(&quot;/people&quot;, GetPeople).Methods(&quot;GET&quot;)<br>    router.HandleFunc(&quot;/people/{id}&quot;, GetPerson).Methods(&quot;GET&quot;)<br>    router.HandleFunc(&quot;/people/{id}&quot;, CreatePerson).Methods(&quot;POST&quot;)<br>    router.HandleFunc(&quot;/people/{id}&quot;, DeletePerson).Methods(&quot;DELETE&quot;)<br>    log.Fatal(http.ListenAndServe(&quot;:8000&quot;, router))<br>}</pre><p>Let’s run our program</p><pre>rest-api$ go build<br>rest-api$ ./rest-api</pre><p>The above would return an error, we haven’t created the functions to handle those requests. Lets create them (blank for now):</p><pre>...<br>func GetPeople(w http.ResponseWriter, r *http.Request) {}<br>func GetPerson(w http.ResponseWriter, r *http.Request) {}<br>func CreatePerson(w http.ResponseWriter, r *http.Request) {}<br>func DeletePerson(w http.ResponseWriter, r *http.Request) {}<br>...</pre><p>Building the file again shouldn’t return any errors, but the functions are empty. Each methods, take two parameters w and r which are of types http.ResponseWriter and *http.Request. These two parameters are populated once hit by a request.</p><h3>Pull all data from the Phonebook</h3><p>Lets write the code to get all records <strong>tires screech»&gt;</strong> We don’t have any data… yeah, lets populate manually (databases are out of scope for this tutorial). Lets add a Person struct (think of it as an object) and an Address struct, and a people variable to populate with.</p><pre>//main.go<br>...<br>type Person struct {<br>    ID        string   `json:&quot;id,omitempty&quot;`<br>    Firstname string   `json:&quot;firstname,omitempty&quot;`<br>    Lastname  string   `json:&quot;lastname,omitempty&quot;`<br>    Address   *Address `json:&quot;address,omitempty&quot;`<br>}<br>type Address struct {<br>    City  string `json:&quot;city,omitempty&quot;`<br>    State string `json:&quot;state,omitempty&quot;`<br>}</pre><pre>var people []Person<br>...</pre><p>With our structs ready, lets manually add records to the people slice:</p><pre>// main()<br>...</pre><pre>people = append(people, Person{ID: &quot;1&quot;, Firstname: &quot;John&quot;, Lastname: &quot;Doe&quot;, Address: &amp;Address{City: &quot;City X&quot;, State: &quot;State X&quot;}})<br>people = append(people, Person{ID: &quot;2&quot;, Firstname: &quot;Koko&quot;, Lastname: &quot;Doe&quot;, Address: &amp;Address{City: &quot;City Z&quot;, State: &quot;State Y&quot;}})<br>people = append(people, Person{ID: &quot;3&quot;, Firstname: &quot;Francis&quot;, Lastname: &quot;Sunday&quot;})</pre><pre>...</pre><p><strong>With our data set, lets fetch all from the people slice:</strong></p><pre>//main.go<br>...</pre><pre>func GetPeople(w http.ResponseWriter, r *http.Request) {<br>    json.NewEncoder(w).Encode(people)<br>}</pre><pre>...</pre><p>Rebuilding (go build &amp;&amp; ./rest-api ) and testing with postman we’d get a JSON response. Navigate to localhost:8080/people</p><h3>Get a single data</h3><p>Now lets write the to show a single person:</p><pre>// main.go<br>...</pre><pre>func GetPerson(w http.ResponseWriter, r *http.Request) {<br>    params := mux.Vars(r)<br>    for _, item := range people {<br>    if item.ID == params[&quot;id&quot;]<br>}<br>}</pre><pre>...</pre><p>The GetPerson function here loops through the mapped names from the incoming request, to check if the id params sent matches any in the Person struct.</p><h3>Other Endpoints</h3><p>Lets finish our other s (CreatePerson, DeletePerson)</p><pre>func CreatePerson(w http.ResponseWriter, r *http.Request) {<br>    params := mux.Vars(r)<br>    var person Person<br>    _ = json.NewDecoder(r.Body).Decode(&amp;person)<br>    person.ID = params[&quot;id&quot;]<br>    people = append(people, person)<br>    json.NewEncoder(w).Encode(people)<br>}<br>func DeletePerson(w http.ResponseWriter, r *http.Request) {<br>    params := mux.Vars(r)<br>    for index, item := range people {<br>        if item.ID == params[&quot;id&quot;] {<br>            people = append(people[:index], people[index+1]...)<br>            break<br>    }<br>    json.NewEncoder(w).Encode(people)<br>}<br>}</pre><h3>Putting it all together</h3><p>Now our Final main.go file should look as such:</p><pre>package main</pre><pre>import (<br>    &quot;encoding/json&quot;<br>    &quot;github.com/gorilla/mux&quot;<br>    &quot;log&quot;<br>    &quot;net/http&quot;<br>)</pre><pre>// The person Type (more like an object)<br>type Person struct {<br>    ID        string   `json:&quot;id,omitempty&quot;`<br>    Firstname string   `json:&quot;firstname,omitempty&quot;`<br>    Lastname  string   `json:&quot;lastname,omitempty&quot;`<br>    Address   *Address `json:&quot;address,omitempty&quot;`<br>}<br>type Address struct {<br>    City  string `json:&quot;city,omitempty&quot;`<br>    State string `json:&quot;state,omitempty&quot;`<br>}</pre><pre>var people []Person</pre><pre>// Display all from the people var<br>func GetPeople(w http.ResponseWriter, r *http.Request) {<br>    json.NewEncoder(w).Encode(people)<br>}</pre><pre>// Display a single data<br>func GetPerson(w http.ResponseWriter, r *http.Request) {<br>    params := mux.Vars(r)<br>    for _, item := range people {<br>        if item.ID == params[&quot;id&quot;] {<br>            json.NewEncoder(w).Encode(item)<br>            return<br>        }<br>    }<br>    json.NewEncoder(w).Encode(&amp;Person{})<br>}</pre><pre>// create a new item<br>func CreatePerson(w http.ResponseWriter, r *http.Request) {<br>    params := mux.Vars(r)<br>    var person Person<br>    _ = json.NewDecoder(r.Body).Decode(&amp;person)<br>    person.ID = params[&quot;id&quot;]<br>    people = append(people, person)<br>    json.NewEncoder(w).Encode(people)<br>}</pre><pre>// Delete an item<br>func DeletePerson(w http.ResponseWriter, r *http.Request) {<br>    params := mux.Vars(r)<br>    for index, item := range people {<br>        if item.ID == params[&quot;id&quot;] {<br>            people = append(people[:index], people[index+1:]...)<br>            break<br>        }<br>        json.NewEncoder(w).Encode(people)<br>    }<br>}</pre><pre>// main function to boot up everything<br>func main() {<br>    router := mux.NewRouter()<br>    people = append(people, Person{ID: &quot;1&quot;, Firstname: &quot;John&quot;, Lastname: &quot;Doe&quot;, Address: &amp;Address{City: &quot;City X&quot;, State: &quot;State X&quot;}})<br>    people = append(people, Person{ID: &quot;2&quot;, Firstname: &quot;Koko&quot;, Lastname: &quot;Doe&quot;, Address: &amp;Address{City: &quot;City Z&quot;, State: &quot;State Y&quot;}})<br>    router.HandleFunc(&quot;/people&quot;, GetPeople).Methods(&quot;GET&quot;)<br>    router.HandleFunc(&quot;/people/{id}&quot;, GetPerson).Methods(&quot;GET&quot;)<br>    router.HandleFunc(&quot;/people/{id}&quot;, CreatePerson).Methods(&quot;POST&quot;)<br>    router.HandleFunc(&quot;/people/{id}&quot;, DeletePerson).Methods(&quot;DELETE&quot;)<br>    log.Fatal(http.ListenAndServe(&quot;:8000&quot;, router))<br>}</pre><h3>Testing</h3><p>To test out yor API, either view them from a browser (you’d need a JSON formatter extension, to read the output clearly) or use <a href="https://getpostman.com/">Postman</a>.</p><blockquote><em>Source for this tutorial can be found </em><a href="https://github.com/HakaseLabs/source-blog/tree/master/rest-api"><em>here</em></a></blockquote><h3>Conclusion</h3><p>You just saw how to build a very simple RESTful API using the Go programming language. While we used mock data instead of a database, we saw how to create endpoints that do various operations with JSON data and GoLang slices. Did I miss anything important? Let me know in the comments.</p><p>:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d5d801ddf02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ph-devconnect/building-a-restful-api-with-go-5d5d801ddf02">Building a RESTful API with Go</a> was originally published in <a href="https://medium.com/ph-devconnect">PH DevConnect</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build your first RESTful API with Node.js]]></title>
            <link>https://medium.com/ph-devconnect/build-your-first-restful-api-with-node-js-e701b53d1f41?source=rss-38ef9ca6edc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e701b53d1f41</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Francis Sunday]]></dc:creator>
            <pubDate>Wed, 14 Jun 2017 13:19:24 GMT</pubDate>
            <atom:updated>2017-06-14T13:19:24.460Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g-_-wt7cl_oZzo9z.jpg" /></figure><p><strong>Node.js</strong> is one intimidating JavaScript framework, especially for beginners. This article serves as a quick quide to Node.js, Express.js and MongoDB. We’ll building a simple REST API that’ll serve as a basic foundation for an application.</p><p>For the purpose of this tutorial, you’ll be creating the base for a <em>ToDo List</em> application (yeah its kinda like the convention to start with ToDo list apps). You’ll use all CRUD (create, read, update and delete) actions on the API.</p><h3>What is REST?</h3><p>REST is an acronym for Representational State Transfer. It is a web standards architecture and HTTP Protocol. The REST protocol, decribes six (6) constraints:</p><ol><li>Uniform Interface</li><li>Cacheable</li><li>Client-Server</li><li>Stateless</li><li>Code on Demand</li><li>Layered System</li></ol><p>REST is composed of methods such as a base URL, media types, etc. RESTful applicaitons uses HTTP requests to perform the CRUD operations.</p><h3>Setup</h3><p>You’ll need to have Node installed, if not in place get in <a href="https://howtonode.org/how-to-install-nodejs">here</a>.</p><p>I’m on Elementary OS (an Ubuntu flavoured distro), so i’ll be using the command line alot.</p><p>In a new directory todoApp or whatever you’d like to name yours, we’ll need a package.json file, so we’ll use npm to generate one:</p><pre>npm init</pre><p>Feel free to use or change the defaults. Once that’s done, you should be a package.json file generated in the root directory.</p><p>We need Express as our web framework, body-parser to help handle JSON requests, MongoDB for the database, and Nodemon to watch for file changes while our app is being served.</p><pre>npm install --save express body-parser mongoose &amp;&amp; npm install --save-dev nodemon</pre><ul><li>You may need root access for npm to write out files, just append sudo to the command to grant root access.</li><li>We’ll be using Mongoose to interact with a MongoDB instance, you’ll still need to have MongoDB server installed on your machine</li></ul><p>After the package installation is done, your complete package.json file should look like this:</p><pre>{<br>  &quot;name&quot;: &quot;todoApp&quot;,<br>  &quot;version&quot;: &quot;0.0.0&quot;,<br>  &quot;description&quot;: &quot;Building a REST API with Node.js&quot;,<br>  <br>  &quot;author&quot;: &quot;Francis Sunday&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;body-parser&quot;: &quot;^1.17.2&quot;,<br>    &quot;express&quot;: &quot;^4.15.3&quot;,<br>    &quot;mongoose&quot;: &quot;^4.10.4&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;nodemon&quot;: &quot;^1.11.0&quot;<br>  }<br>}</pre><h3>Serving up the App</h3><p>If you check your directory you’d notice a new folder node_modules that’s where the dependencies were saved by the npm install command. We need to require them and start up our app. Go ahead and create a server.js file with this content:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br>const port = process.env.PORT || 3000;<br>const mongoose = require(&#39;mongoose&#39;);<br>const bodyParser = require(&#39;body-parser&#39;);</pre><pre>// get our server running<br>app.listen(port, () =&gt; {<br>    console.log(&quot;App up and running on&quot; + port);<br>});</pre><p>Now run node server.js and you’d see the log.</p><h3>File Structure</h3><p>We need to structure or directory so we have dedicated files for various actions — routes, models, and controllers. Go ahead and create the following directory structure:</p><pre>--todoApp<br>    - api<br>        - models<br>        - controllers<br>        - routes<br>    - node_modules<br>    - server.js<br>    - package.json<br>    ...</pre><p>We create the dedicated files in their directories- ` api/models/todoModel.js api/controllers/todoController.js api/routes/todoRoutes.js `</p><p>Your directory structure should look like this now:</p><pre>--todoApp<br>    - api<br>        - models<br>            - todoModel.js<br>        - controllers<br>            - todoController.js<br>        - routes<br>            - todoRoutes.js<br>    - node_modules<br>    - server.js<br>    - package.json<br>    ...</pre><h3>CRUD Routes</h3><p>For this api, you’ll create four (4) different routes, to handle CREAting a todo item, READing an item, UPDATE and item, and DELETE an item. You’re also gonna need to test your API while developing, so we’ll use an awesome app called <a href="https://getpostman.com/">Postman</a>, which will allow us make simple HTTP requests.</p><h4>Your First Route</h4><p>Routing refers to determining how an application responds to requests, which is a URI and a specific request method (POST, GET, DELETE, etc).</p><p>We’re gonna define two basic routes /tasks and /tasks/{taskid}</p><pre>// api/models/todoRoutes.js</pre><pre>module.exports = (app) =&gt; {<br>    let todoList = require(&#39;../controllers/todoController&#39;);</pre><pre>    // our Routes<br>    app.route(&#39;/tasks&#39;)<br>        .get(todoList.getTasks) <br>        .post(todoList.createTask);<br>    <br>    app.route(&#39;/tasks/:taskId&#39;)<br>        .get(todoList.readTask)<br>        .put(todoList.updateTask)<br>        .delete(todoList.deleteTask);<br>}</pre><p>In the code above, the API’s routes are defined under different verbs; when a request is made for the tasks route e.g todoApp.dev/tasks, it calls the getTasks method from the required todoList controller, same for the post, put, and delete routes. The tasks/:taskId route, handles a single task. We can grab a task via its ID - /tasks/3 update or delete it too.</p><h3>Database Schema</h3><p>We’ll be using Mongoose to interact with a MongoDB instance. In the todoModel.js file, we’ll define a schema for our Tasks collection. With Mongoose, we can create Schemas easily by defining the fields and their types.</p><blockquote><em>You’ll need to have MongoDB server installed locally, if you want to serve your database. You can also use a remote database, there’s a free tier from </em><a href="https://hakaselabs.github.io/2017/07/13/building-a-restful-api-nodejs/%27https://mlab.com"><em>MLab</em></a></blockquote><pre>const mongoose = require(&#39;mongoose&#39;);<br>const Schema = mongoose.Schema;</pre><pre>let TaskSchema = new Schema({<br>    name: {<br>        type: String,<br>        Required: &#39;Task label is required!&#39;<br>    },<br>    Created_date: {<br>        type: Date,<br>        default: Date.now<br>    },<br>    status: {<br>        type: [{<br>            type: String,<br>            enum: [&#39;completed&#39;, &#39;ongoing&#39;, &#39;pending&#39;]<br>        }],<br>        default: [&#39;pending&#39;]<br>    }<br>});</pre><pre>module.exports = mongoose.model(&#39;Tasks&#39;, TaskSchema);</pre><p>In the taskModel file, we created a schema for it. As you can see, it the task collection(table) will contain a name: a string, and the date it was created.</p><h3>Setting up Controllers</h3><p>Remember those methods attached to each verb in the todoRoutes.js file, they are controller methods, and we are creating them in the api/controllers/todoController.js file:</p><pre>const mongoose = require(&quot;mongoose&quot;);<br>const Task = mongoose.model(&quot;Tasks&quot;);</pre><pre>// get all tasks</pre><pre>exports.getTasks = (req, res) =&gt; {<br>    Task.find({}, (err, task) =&gt; {<br>        if (err)<br>            res.send(err);<br>        <br>        res.json(task);<br>    });<br>};</pre><pre>// create a task</pre><pre>exports.createTask = (req, res) =&gt; {<br>    let newTask = new Task(req.body);<br>    newTask.save( (err, task) =&gt; {<br>        if (err)<br>            res.send(err);<br>        <br>        res.json(task);<br>    });<br>};</pre><pre>// read a single task </pre><pre>exports.readTask = (req, res) =&gt; {<br>    Task.findById(req.params.id, (err, task) =&gt; {<br>        if (err)<br>            res.send(err);</pre><pre>        res.json(task);<br>    });<br>};</pre><pre>// update a particular task </pre><pre>exports.updateTask = (req, res) =&gt; {<br>  Task.findOneAndUpdate(req.params.id, req.body, { new: true }, (err, task) =&gt; {<br>    if (err) <br>        res.send(err);</pre><pre>    res.json(task);<br>  });<br>};</pre><pre>// delete a single task </pre><pre>exports.deleteTask = (req, res) =&gt; {<br>    Task.remove({<br>        _id: req.params.id<br>    }, (err, task) =&gt; {<br>        if (err)<br>            res.send(err);<br>        res.json({ message: &#39;Task deleted!!&#39; });<br>    });<br>};</pre><h3>Coupling everything</h3><p>Back in our server.js file, we’ll connect to our database, by adding a URL to the mongoose connection instance, Load the created Model (task), register our created routes. Update your server.js file to look like this:</p><pre>const express = require(&quot;express&quot;); // express framework<br>const app = express();<br>const port = process.env.PORT || 3000;<br>const mongoose = require(&quot;mongoose&quot;);<br>const Task = require(&quot;./api/models/todoListModel&quot;);<br>const bodyParser = require(&#39;body-parser&#39;);</pre><pre>mongoose.Promise = global.Promise;<br>mongoose.connect(&quot;mongodb://localhost:2701/todoApp&quot;); // connect to MongoDB</pre><pre>// handle incoming requests<br>app.use(bodyParser.urlencoded({ extended: true }));<br>app.use(bodyParser.json());</pre><pre>// middleware to handle wrong routes </pre><pre>app.use( (req, res) =&gt; {<br>    res.status(404).send({ url: req.originalUrl + &#39;not found&#39; });<br>});</pre><pre>let routes = require(&quot;./api/routes/todoListRoute&quot;);<br>routes(app); // register our routes</pre><pre>app.listen(port); <br>console.log(&#39;App running on &#39; + port);</pre><h3>Testing with Postman</h3><p>To test your API using postman, startup the server nodemon server.js and then open up the postman app and pass in your url</p><h4>Get all tasks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/0*oVBDQDhSCcNwaucF.png" /></figure><h4>Create a Task</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/0*4j5uHJBDTT6so88n.png" /></figure><blockquote><em>Note: To use the post method on postman, the </em>Body<em> should be set to </em>x-www-form-urlencode</blockquote><h3>That’s it!</h3><p>You have a working Node.js API which makes use of the four major HTTP verbs (GET, POST, PUT, DELETE).</p><p>This tutorial was created to give you a familarity with the Node.js development environment along side Express.js and MongoDB.</p><p>Was this helpful? feel free to leave a comment below. Also, if you have questions, noticed an error, please do well to let me know.</p><p>Thanks!</p><p><strong><em>Originally published on </em></strong><a href="https://hakaselabs.github.io/"><strong><em>HakaseLabs</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e701b53d1f41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ph-devconnect/build-your-first-restful-api-with-node-js-e701b53d1f41">Build your first RESTful API with Node.js</a> was originally published in <a href="https://medium.com/ph-devconnect">PH DevConnect</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Twitter Bots]]></title>
            <link>https://medium.com/ph-devconnect/an-introduction-to-twitter-bots-a6c21b5122c4?source=rss-38ef9ca6edc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6c21b5122c4</guid>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[how-to]]></category>
            <dc:creator><![CDATA[Francis Sunday]]></dc:creator>
            <pubDate>Tue, 30 May 2017 15:33:19 GMT</pubDate>
            <atom:updated>2017-05-30T15:40:45.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzgSNMk2jhz_GC2C5rXDNw.gif" /></figure><p>This was my first attempt making twitter bots (production ready). I made a very simple twitter bot for this blog, check the <a href="https://github.com/codehakase/hakasebot">Source</a> and also follow <a href="https://twitter.com/_hakasebot">@_hakasebot</a>.</p><h3>Setting Up</h3><p>The bot was created using the <a href="https://github.com/ttezel/twit">Twit</a> package, which is a Twitter API client for Node.js. Twit needs to connect with my twitter account so first I created a new <a href="https://apps.twitter.com/">Twitter Application</a>. After that, I took note of my application’s keys:</p><ul><li>Consumer Key</li><li>Consumer Secret</li><li>Access Token</li><li>Access Token Secret</li></ul><p>You can find these keys on the <strong>Keys and Access Tokens</strong> panel in you app’s dashboard.</p><p>Once these keys are all ready, we create a new Node.js project and initialise the Twit package.</p><blockquote><em>Prerequisites: Node.js, npm, and of course a PC</em></blockquote><p>So you can create a directory and create three files package.json, config.js, and bot.js</p><p>In the config.js file, we setup Twit.</p><pre>//config.js<br>const Twit = require(&#39;twit&#39;);<br>const TH = new Twit({ // Twit Handler<br>    consumer_key: APPLICATION_CONSUMER_KEY_HERE,<br>    consumer_secret: APPLICATION_CONSUMER_SECRET_HERE,<br>    access_token: ACCESS_TOKEN_HERE,<br>    access_token_secret: ACCESS_TOKEN_SECRET_HERE<br>});</pre><p>Basically, @_hakasebot does the following:</p><ul><li>Listens for Events and keywords</li><li>Responds to Events</li><li>Like</li><li>Retweet</li><li>Reply</li></ul><h3>Listens for Events and Keywords</h3><p>Twitter has a <a href="https://dev.twitter.com/streaming/overview">Streaming API</a>, which gives us access to the streams of tweets. @_hakasebot uses two streams from the API:</p><ul><li>The <strong>User Stream</strong>, which is a stream of tweets corresponding to a single user.</li><li>The <strong>Public Stream</strong>, which is the stream of all public tweets.</li></ul><p>With the <em>public</em> stream, @_hakasebot can listen for tweets from any users that contains a defined keyword. This is possible when we create a stream of tweets based on a filter suing the <strong>statuses/filter</strong> endpoint, and passing an object with the filter parameters. The <strong>track</strong> parameter is used to filter tweets by keyword, and it accepts a string or an array of keywords to lookout for.</p><p>@_hakasebot runs on a filter that searches for mentions of this blog, so we’d implement as so:</p><pre>const stream = TH.stream(&#39;statuses/filter&#39;, {<br>    track: [&#39;hakasebot&#39;, &#39;hakaselabs&#39;, &#39;hakaselabs.github.io&#39;]<br>});</pre><p>When a stream if open, we can listen and respond to tweets that falls within that stream.</p><pre>stream.on(&#39;tweet&#39;, (tweet) =&gt; {<br>    // We do something with that tweet here<br>});</pre><h3>Responding to Events</h3><p>We can respond to events by posting a tweet, retweeting, replying, follow a user, etc. @_hakasebot is able to take three actions currently — like, reply, and retweet.</p><h3>Liking a tweet</h3><p>if the tweet was from another account, the bot likes it. To like a tweet, we post to the <strong>/favourites/create</strong> endpoint, passing the id of the tweet to be favorited.</p><pre>stream.on(&#39;tweet&#39;, (tweet) =&gt; {<br>    if (tweet.user.id == _self.id) { // <br>        // we&#39;ll get back to this <br>    }<br>    TH.post(&#39;favourites/create&#39;, {<br>        id: tweet.id_str<br>    });<br>});</pre><h3>Replying a tweet</h3><p>If the tweet was from another user, the bot sends them a reply. We send a reply by posting to the <strong>/statuses/update</strong> endpoint and passing the id of the tweet we are replying to.</p><pre>stream.on(&#39;tweet&#39;, (tweet) =&gt; {<br>    if (tweet.user.id == _self.id) {....}</pre><pre>    TH.post(&#39;favourites/create&#39;, {<br>        id: tweet.id_str<br>    });<br>    TH.post(&#39;statuses/update&#39;, {<br>        status: `@${tweet.user.screen_name} Thanks for sharing :)`,<br>        in_reply_to_status_id: tweet.id_str <br>    });<br>});</pre><h3>Retweeting</h3><p>@_hakasebot retweets a tweet if it is found from my stream — That means if the tweet found from the stream is from myself <a href="https://twitter.com/codehakase">@codehakase</a>, it retweets it. We can retweet by posting to the <strong>/statuses/retweet/:id</strong> endpoint.</p><pre>const _self = {<br>    id: 3354871743,<br>    screen_name: &#39;codehakase&#39;<br>}<br>...</pre><pre>stream.on(&#39;tweet&#39;, (tweet) =&gt; {<br>    if (tweet.user.id == _self.id) {<br>        TH.post(&#39;statuses/retweet/:id&#39;, {<br>            id: tweet.id_str<br>        });<br>        return;<br>    }<br>    ....<br>});</pre><blockquote><em>You can get your twitter account id from </em><a href="http://gettwitterid.com/"><em>here</em></a></blockquote><h3>Deploying the Bot</h3><p>I used <a href="http://heroku.com/">Heroku</a> to host @_hakasebot. Since its a Node.js app, we need to place some information in our package.json file:</p><ul><li>The main script — The file Node.js would run</li><li>Dependencies</li><li>The version of Node.js</li></ul><p>My package.json file looks this way:</p><pre>{<br>  &quot;name&quot;: &quot;hakasebot&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;A twitter bot for hakaselabs.github.io&quot;,<br>  &quot;main&quot;: &quot;bot.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node bot.js&quot;<br>  },<br>  &quot;author&quot;: &quot;Francis Sunday - codehakase&quot;,</pre><pre>  &quot;dependencies&quot;: {<br>    &quot;twit&quot;: &quot;^2.2.5&quot;,<br>    &quot;express&quot;: &quot;^4.14.0&quot;<br>  },<br>  &quot;engines&quot;: {<br>    &quot;node&quot;: &quot;7.9.0&quot;<br>  }<br>}</pre><p>Great! you now have an idea of how to make bots for Twitter. You can follow <a href="https://twitter.com/_hakasebot">@_hakasebot</a>, view the <a href="https://github.com/codehakase/hakasebot">source</a>, to test, use the twitter share button below.</p><p>Have you built bots for Twitter? I’d like to know, drop them in the comment section below.</p><blockquote><strong>As originally published by </strong><a href="https://twitter.com/codehakase"><strong>me</strong></a><strong> on </strong><a href="https://hakaselabs.github.io/"><strong>hakaselabs.github.io</strong></a></blockquote><blockquote><strong>PHDevConnect</strong> is a free, open community of Port Harcourt based Developers, UI / UX Designers, Project managers, Architects etc who can create their own digital team or join other teams for paid/open sourced projects.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6c21b5122c4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ph-devconnect/an-introduction-to-twitter-bots-a6c21b5122c4">An Introduction to Twitter Bots</a> was originally published in <a href="https://medium.com/ph-devconnect">PH DevConnect</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object-Oriented PHP — An Easy Approach]]></title>
            <link>https://medium.com/ph-devconnect/object-oriented-php-an-easy-approach-6774c425854a?source=rss-38ef9ca6edc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6774c425854a</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Francis Sunday]]></dc:creator>
            <pubDate>Wed, 17 May 2017 23:36:51 GMT</pubDate>
            <atom:updated>2017-05-19T11:48:56.576Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*oAIfjxo_whV0EIdVKdUt2w.png" /></figure><p>For some PHP developers, the concept of object-orient programming, seems like a frightening concept. You might have browsed through repos on GitHub or read articles on how to implement a feature in a particular PHP project of yours, and the code is full of complicated syntax. I tell you, the concept of OOP is easy to grasp.</p><p><strong>Object-Oriented programming</strong> (OOP), is a style of programming which allows us developers and programmers group related tasks or actions into classes to produce effective code. OOP follows the tenet <em>“don’t repeat yourself (DRY)</em>, which are common in procedural programming.</p><h3>Why Learn OOP?</h3><p>Many frameworks built upon PHP are using the OOP paradigm and if you intend learning one of those frameworks (Laravel, Codeigniter, Symfony, etc), you’ll need a ground on OOP to start with.</p><h3>Objects and Classes</h3><p>In OOP there are two major concepts you’d see often (they really make up OOP), they are <strong>objects</strong> and <strong>classes</strong>. These terms sometimes appear to be interchangeable. That is not the case. A class for example, stands as a <strong>structure</strong> or <em>blueprint</em>. Relate that to a Building, say a Bank, a blueprint is presented which defines the properties of the buildings, and once accepted they proceed to erect the building. <em>Classes</em> form the structure of data needed to build objects. That same bank can use the same blueprint and erect same structure in a different location with slight differences (branch manager, number of staff, etc).</p><h3>Creating Classes</h3><p>The syntax to create a class in PHP is very straightforward, the class key word is used to declare a class, followed by the name and a pair of curly braces { ... }</p><pre>&lt;?php </pre><pre>class OurClass <br>{<br>  // properties and methods<br>}</pre><p>So we can write a basic User class as such</p><pre>&lt;?php <br>class User<br>{<br>  public $firstname;<br>  public $lastname;</pre><pre>  public function __construct($firstname, $lastname)<br>  {<br>    $this-&gt;firstname = $firstname;<br>    $this-&gt;lastname = $lastname;<br>  }</pre><pre>  public function showInfo()<br>  {<br>    return $this-&gt;firstname . &quot; &quot; . $this-&gt;lastname;<br>  }<br>}<br>// using the class<br>$administrator = new User(&quot;John&quot;, &quot;Doe&quot;);<br>echo $administrator-&gt;showInfo(); // should output</pre><p>The code above, creates a basic blueprint for a user, the __construct method, is a <em>magic</em> method. The method is called when ever the class is <strong>instantiated</strong>. The constructor accepts two parameters $firstname and $lastname and these are passed to the class properties $this-&gt;firsname and $this-&gt;lastname.</p><p>$this refers to the current class in scope.</p><p>Also in the User class, there’s a showInfo method, that dumps the data in a raw format.</p><p>To instantiate a class, you use the new keyword – $obj = new SomeClass;. When a class is instantiated, it creates a copy of the blueprint to that object. We can have various objects as instance of the same class, but their data will vary.</p><p>Add to the code</p><pre>&lt;?php <br>use Codehakase\User;</pre><pre>$user_a = new User(&quot;Francis&quot;, &quot;Sunday&quot;);<br>$user_a-&gt;showInfo();<br>echo &quot;&lt;br&gt;&quot;;<br>$user_b = new User(&quot;Desiigner&quot;, &quot;Doe&quot;);<br>$user_b-&gt;showInfo();</pre><p>Load up the script in your favorite browser localhost/dir/oop.php, you should see an output similar to this:</p><pre>/var/www/html/tuts/backend/PHP/oop.php:15:<br>object(User)[1]<br>  public &#39;firstname&#39; =&gt; string &#39;John&#39; (length=4)<br>  public &#39;lastname&#39; =&gt; string &#39;Doe&#39; (length=3)</pre><pre>/var/www/html/tuts/backend/PHP/oop.php:15:<br>object(User)[2]<br>  public &#39;firstname&#39; =&gt; string &#39;Francis&#39; (length=7)<br>  public &#39;lastname&#39; =&gt; string &#39;Sunday&#39; (length=6)</pre><pre>/var/www/html/tuts/backend/PHP/oop.php:15:<br>object(User)[3]<br>  public &#39;firstname&#39; =&gt; string &#39;Desiigner&#39; (length=9)<br>  public &#39;lastname&#39; =&gt; string &#39;Doe&#39; (length=3)</pre><p>Awesome!! each instance of the User class is independent of the others, their data is not same.</p><h3>Method and Property Visibility</h3><p>Now the public keyword, is a visibility type. There are three of them public, protected, and private. Also in addition to a property or method visiblity, there’s static keyword, which allows them to accessed even without an instantiation of the class. Any property (variable) or method (class functions) with the public keyword, is accessible anywhere, within and outside the class.</p><p>Any property or method declared as protected can only be accessible within that class and its child classes.</p><p>A property or method declared as private, is only accessible from within the class it was defined in.</p><h3>Comparing Procedural code and Object-Oriented code</h3><p><em>OOP actually provides an easier approach to dealing with data. Because an object can store data internally, variables don’t need to be passed from function to function to work properly.</em> Consider the following getter, setter procedural code</p><pre>&lt;?php<br>function sample() {<br>  return [<br>    //<br>  ]<br>}<br>// a basic setter function </pre><pre>function sampleSet($sample, $name, $value) {<br>  $sample[&#39;vars&#39;][$name] = $value; // creates a multidimensional array from function arguments<br>  return $sample; //returns the loaded array<br>}</pre><pre>// a basic getter <br>function sampleGet($sample, $name) {<br>  if (isset($sample[&#39;vars&#39;][$name])) {<br>    $value = $sample[&#39;vars&#39;][$name];<br>    return [<br>      $sample,<br>      $value<br>    ]<br>  }</pre><pre>  // using the functions <br>  $ex = sample();<br>  $ex = sampleSet($ex, &#39;Helo&#39;, &#39;World&#39;); // set an item<br>  list($ex, $value) = sampleGet($ex, &#39;World&#39;); // grab an item<br>}<br>?&gt;</pre><p>Now I’ll re-write that in an OOP style.</p><pre>&lt;?php<br>class Sample<br>{<br>  private $vars;</pre><pre>  public function set($name, $value)<br>  {<br>    $this-&gt;var[$name] = $value;<br>  }</pre><pre>  public function get($name)<br>  {<br>    return isset($this-&gt;vars[$name]) ? $this-&gt;vars[$name] : null;<br>  }<br>}</pre><pre>// using <br>$ex = new Sample;<br>$ex-&gt;set(&quot;Hello&quot;, &quot;World&quot;);<br>$value = $example-&gt;get(&quot;World&quot;);</pre><pre>var_dump($ex);<br>?&gt;</pre><p>Running the OOP code, you get something similar to:</p><pre>/var/www/html/tuts/backend/PHP/oop.php:49:<br>object(Sample)[4]<br>  private &#39;vars&#39; =&gt; null<br>  public &#39;var&#39; =&gt; <br>    array (size=1)<br>      &#39;Hello&#39; =&gt; string &#39;World&#39; (length=5)</pre><h3>Better Code Management</h3><p>With OOP, you can manage your files within your application easily, by making use of autoloading.</p><p>A typical Procedural dependencies script may look as such:</p><pre>&lt;?php<br>require_once &quot;php-includes/connect.php&quot;<br>require_once &quot;php-includes/do-login.php&quot;<br>require_once &quot;php-includes/reset-password.php&quot;<br>require_once &quot;php-includes/do-signup.php&quot;<br>...</pre><p>We can use class autoloading to include all the files we want</p><pre>function __autoload($class) {<br>  include_once &#39;inc/class&#39; . $class . &#39;.php&#39;;<br>}</pre><p>Preferably, i use <a href="https://getcomposer.org/">Composer</a> and the <a href="https://getcomposer.org/doc/04-schema.md#psr-4">PSR-4</a> autoloading standard, for everything autoloading. A basic Autoload with composer would look like this:</p><pre>{<br>  &quot;autoload&quot;: {<br>    &quot;psr-4&quot;: {<br>      &quot;Codehakase\\&quot;: &quot;app/&quot;<br>    }<br>  }<br>}</pre><pre>&lt;?php <br>require_once &quot;vendor/autoload.php&quot; // composer&#39;s autoloader</pre><pre>use Codehakase\Models\User;</pre><pre>$user = new User;</pre><pre>$user-&gt;learnOOP(true);<br>...</pre><h3>Conclusion</h3><p>It’s been awesome walking you through the concept of object-oriented programming in PHP. Learning or mastering OOP is a really great way to up your programming skills to the next level as a PHP Developer. We are still gonna continue learning other concepts of OOP, and build a real application with it. All this to come in subsequent articles after this.</p><p>Got any questions or suggestions? Drop them in the comment box below.</p><blockquote><strong>PHDevConnect</strong> is a free, open community of Port Harcourt based Developers, UI / UX Designers, Project managers, Architects etc who can create their own digital team or join other teams for paid/open sourced projects.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6774c425854a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ph-devconnect/object-oriented-php-an-easy-approach-6774c425854a">Object-Oriented PHP — An Easy Approach</a> was originally published in <a href="https://medium.com/ph-devconnect">PH DevConnect</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello World!!]]></title>
            <link>https://medium.com/ph-devconnect/hello-world-81d60dbfb418?source=rss-38ef9ca6edc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/81d60dbfb418</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[community]]></category>
            <category><![CDATA[skills]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Francis Sunday]]></dc:creator>
            <pubDate>Thu, 04 May 2017 15:50:52 GMT</pubDate>
            <atom:updated>2017-05-04T15:50:52.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1kZAWn_PgLE1LFsri28oxA.png" /><figcaption>Developer that didn’t use this phrase, is that one a Developer !!!</figcaption></figure><p>Over the past years, there has been a lot of things going on in the Developer community in Africa. The community is now on a global scale, with world class developers coming out from the heart of Africa.</p><p>Technology, has taken a firm stand on the African Soil, and many are taking the lead from the rest of the world. It’s a true fact that the Tech community in Nigeria has increased over the years, so many has ventured into one niche or another in Technology, with conferences and meetups holding almost everyday. And this community is not gender specific (no longer a male dominated thing).</p><blockquote>PHDevConnect, was created with the foremost goal of identifying and connecting Software Developers, Tech enthusiasts and generalists in Port Harcourt (a city in Rivers, Nigeria) by putting up their stories, projects at the fore front for the world to see.</blockquote><p>PHDevConnect is a free, open community of Port Harcourt based Developers, UI / UX Designers, Project managers, Architects etc who can create their own digital team or join other teams for paid/open sourced projects. Its somewhat true that in Port Harcourt, there are bad ass Techies, but majority are on a low-key, so we set out to connect to all and get them under one domain (though there are other communities existing).</p><blockquote>PDC main focus is on newbie techies, and those looking out to join a community (especially in Software Development, you become better when you peer program).</blockquote><p>By sharing our stories (and code of course), we hope to inspire other developers/techies in and out of Port Harcourt (and the world at large). We plan on taking this community further in future, we hope to start outsourcing members of <strong>PDC</strong> to work on Paid projects so as to expose them to team collaborations.</p><blockquote>Need to join us? yeah for the now, we have a <a href="https://chat.whatsapp.com/invite/4J97iRBioNw5Xam9KheLir"><strong>Whatsapp</strong></a> user group, and a <strong>Slack team</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*n4TTYmRK_mhJykOmXInzJw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81d60dbfb418" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ph-devconnect/hello-world-81d60dbfb418">Hello World!!</a> was originally published in <a href="https://medium.com/ph-devconnect">PH DevConnect</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>