<?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 Etienne Rouzeaud on Medium]]></title>
        <description><![CDATA[Stories by Etienne Rouzeaud on Medium]]></description>
        <link>https://medium.com/@etiennerouzeaud?source=rss-fd941f66a978------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5OT2r1pUaj_mw-r-L0fKaA.jpeg</url>
            <title>Stories by Etienne Rouzeaud on Medium</title>
            <link>https://medium.com/@etiennerouzeaud?source=rss-fd941f66a978------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 07:59:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@etiennerouzeaud/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[How create an API RESTfull in Express (Node.js) without Database]]></title>
            <link>https://medium.com/@etiennerouzeaud/how-create-an-api-restfull-in-express-node-js-without-database-b030c687e2ea?source=rss-fd941f66a978------2</link>
            <guid isPermaLink="false">https://medium.com/p/b030c687e2ea</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[express]]></category>
            <dc:creator><![CDATA[Etienne Rouzeaud]]></dc:creator>
            <pubDate>Wed, 19 Sep 2018 10:51:40 GMT</pubDate>
            <atom:updated>2018-09-19T10:51:40.768Z</atom:updated>
            <content:encoded><![CDATA[<p>When you develop a SPA (Single Page Application), the most part of time, you need to contact an API. With a JSON file, Promises, native JavaScript functions and of course, Express, I will show you how to prepare a basic API RESTful.</p><h3>Prepare the server</h3><h4>Initialized the project</h4><p>Before, make sure, you have Node.js and NPM installed both.</p><pre>node -v &amp;&amp; npm -v</pre><p>Then, create a new project with <strong>npm</strong> command.</p><pre>npm init -y</pre><p>And install packages like <strong>express</strong>, <strong>morgan</strong> and <strong>nodemon</strong>. 📦📦📦</p><pre>$ npm install express</pre><pre>$ npm install --save-dev morgan nodemon</pre><h4>First route</h4><p>Create a new file <strong>index.js</strong>.</p><pre>touch index.js</pre><p>And copy paste this code to create a simple server running on port 1337.</p><pre>// Import packages<br><em>const</em> express = require(&#39;express&#39;)<br><em>const</em> morgan = require(&#39;morgan&#39;)</pre><pre>// App<br><em>const</em> app = express()</pre><pre>// Morgan<br>app.use(morgan(&#39;tiny&#39;))</pre><pre>// First route<br>app.get(&#39;/&#39;, (<em>req</em>, <em>res</em>) <em>=&gt;</em> {<br>    res.json({ message: &#39;Hello world&#39; })<br>})</pre><pre>// Starting server<br>app.listen(&#39;1337&#39;)</pre><h4>Launch server with Nodemon</h4><p>Open <strong>package.json</strong> in your editor and add a line in the script object, before “test”.</p><pre><em>&quot;</em>dev&quot;: &quot;node_modules/.bin/nodemon -e js&quot;,</pre><p>If you use a Node version ≤ 8.2.1, you will need to add the “ — harmony<strong>”</strong> flag for using spread operator.</p><pre><em>&quot;</em>dev&quot;: &quot;node_modules/.bin/nodemon --harmony -e js&quot;,</pre><p>Save modifications and run the command in your terminal.</p><pre>npm run dev</pre><p>Open your navigator and go to <a href="http://localhost:1337/">http://localhost:1337</a> or with CURL command.</p><pre>curl -i <a href="http://localhost:1337/">http://localhost:1337</a></pre><p>Will returns this result.</p><pre>HTTP/1.1 200 OK<br>Content-Type: application/json; charset=utf-8<br>Content-Length: 25<br>Connection: keep-alive</pre><pre>{&quot;message&quot;:&quot;Hello world&quot;}</pre><p>Wonferful! We have an object named “message” with the value “Hello world”.</p><h3>Our API content</h3><h4>CRUD operations</h4><p>For each operation, we will need some JavaScript natives functions.</p><ul><li><strong>Create</strong> : <em>array.push()</em></li><li><strong>Read</strong> : <em>array</em></li><li><strong>Read One</strong> : <em>array.find()</em> (return an object)</li><li><strong>Update</strong> : <em>array.find()</em>, <em>array.findIndex() </em>(return the index )</li><li><strong>Delete</strong> : <em>array.find()</em>, <em>array.filter()</em></li></ul><p>For <strong>Create</strong>, <strong>Update </strong>and <strong>Delete</strong>, the data array will be updated in the JSON file.</p><h4>File organisation</h4><p>Adding some folders and files like helper, models, routes and data.</p><pre>└── helpers<br>    ├── helper.js<br>    └── middlewares.js<br>└── data<br>    └──posts.json<br>└── models<br>    └── post.model.js<br>└── routes<br>    ├── index.routes.js<br>    └── post.routes.js</pre><p>You can create these folders and files with this command.</p><pre>mkdir helpers &amp;&amp; cd helpers &amp;&amp; touch helper.js &amp;&amp; touch middlewares.js &amp;&amp; cd ../ &amp;&amp; mkdir models &amp;&amp; cd models &amp;&amp; touch post.model.js &amp;&amp; cd ../ &amp;&amp; mkdir routes &amp;&amp; cd routes &amp;&amp; touch index.routes.js &amp;&amp; touch post.routes.js &amp;&amp; cd ../ &amp;&amp; mkdir data &amp;&amp; cd data &amp;&amp; touch posts.json &amp;&amp; cd ../</pre><h4>Schema</h4><p>Let create a blog post (very original…) with these fields in a row.</p><ul><li><strong>id</strong> : <em>Number</em> (unique and increment)</li><li><strong>created_at</strong> : <em>Date </em>(<a href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>)</li><li><strong>updated_at</strong> : <em>Date</em> (<a href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>)</li><li><strong>title</strong> : <em>String</em></li><li><strong>content</strong> : <em>String</em></li><li><strong>tags</strong> : <em>Array</em></li></ul><h3>Data</h3><p>Example of data in the <strong>posts.json</strong>.</p><pre>[<br>    {<br>        &quot;id&quot;: 1,<br>        &quot;title&quot;: &quot;First post&quot;,<br>        &quot;content&quot;: &quot;Lorem Ipsum&quot;,<br>        &quot;tags&quot;: [&quot;tag1&quot;, &quot;tag2&quot;, &quot;tag3&quot;],<br>        &quot;createdAt&quot;: &quot;Mon Aug 27 2018 15:16:17 GMT+0200 (CEST)&quot;,<br>        &quot;updatedAt&quot;: &quot;Mon Aug 27 2018 15:16:17 GMT+0200 (CEST)&quot;<br>    },<br>    {<br>        &quot;id&quot;: 2,<br>        &quot;title&quot;: &quot;Second post&quot;,<br>        &quot;content&quot;: &quot;Lorem Ipsum again&quot;,<br>        &quot;tags&quot;: [&quot;tag2&quot;, &quot;tag4&quot;],<br>        &quot;createdAt&quot;: &quot;Mon Aug 27 2018 16:17:18 GMT+0200 (CEST)&quot;,<br>        &quot;updatedAt&quot;: &quot;Mon Aug 27 2018 16:17:18 GMT+0200 (CEST)&quot;<br>    }<br>]</pre><h3>Helper</h3><p>Open the <strong>helper.js</strong> file.</p><pre>const fs = require(&#39;fs&#39;)</pre><pre>const getNewId = (array) =&gt; {<br>    if (array.length &gt; 0) {<br>        return array[array.length - 1].id + 1<br>    } else {<br>        return 1<br>    }<br>}</pre><pre>const newDate = () =&gt; new Date().toString()</pre><pre>function mustBeInArray(array, id) {<br>    return new Promise((resolve, reject) =&gt; {<br>        const row = array.find(r =&gt; r.id == id)<br>        if (!row) {<br>            reject({<br>                message: &#39;ID is not good&#39;,<br>                status: 404<br>            })<br>        }<br>        resolve(row)<br>    })<br>}</pre><pre>function writeJSONFile(filename, content) {<br>    fs.writeFileSync(filename, JSON.stringify(content), &#39;utf8&#39;, (err) =&gt; {<br>        if (err) {<br>            console.log(err)<br>        }<br>    })<br>}</pre><pre>module.exports = {<br>    getNewId,<br>    newDate,<br>    mustBeInArray,<br>    writeJSONFile<br>}</pre><p>We have 4 functions very useful for models.</p><ul><li><strong>getNewId</strong> : searching in the array the last id and increment of 1 to return a new id.</li><li><strong>newDate</strong> : return the date of your server in ISO 8601.</li><li><strong>mustBeInArray</strong>: return a promise. Using when we need to check if a row exist via the id (<strong>Read One</strong>, <strong>Update</strong> and <strong>Delete</strong>).</li><li><strong>writeJSONFile</strong> : write new array in the JSON File data.</li></ul><h3>Middlewares</h3><p>Open the <strong>middlewares.js </strong>file.</p><pre>function mustBeInteger(req, res, next) {<br>    const id = req.params.id</pre><pre>    if (!Number.isInteger(parseInt(id))) {<br>        res.status(400).json({ message: &#39;ID must be an integer&#39; })<br>    } else {<br>        next()<br>    }<br>}</pre><pre>function checkFieldsPost(req, res, next) {<br>    const { title, content, tags } = req.body</pre><pre>    if (title &amp;&amp; content &amp;&amp; tags) {<br>        next()<br>    } else {<br>        res.status(400).json({ message: &#39;fields are not good&#39; })<br>    }<br>}</pre><pre>module.exports = {<br>    mustBeInteger,<br>    checkFieldsPost<br>}</pre><p>We have 2 functions very useful for routes.</p><ul><li><strong>mustBeInteger</strong> : check before to continue if the id is an integer. Using when we need to get the id (<strong>Read One</strong>, <strong>Update</strong> and <strong>Delete</strong>).</li><li><strong>checkFieldsPost</strong> : check before to continue if data. Using when we need to get the id (<strong>Create</strong> and<strong> Update</strong>).</li></ul><h3>Model</h3><p>Open the <strong>post.model.js</strong> file.</p><pre>const filename = &#39;../data/posts.json&#39;<br>let posts = require(filename)<br>const helper = require(&#39;../helper.js&#39;)</pre><pre>function getPosts() {}<br>function getPost(id) {}<br>function insertPost(<em>newPost</em>) {}<br>function updatePost(id, newPost) {}<br>function deletePost(id) {}</pre><pre>module.exports = {<br>    insertPost,<br>    getPosts,<br>    getPost, <br>    updatePost,<br>    deletePost<br>}</pre><p>We load the JSON data file and the helper file. Then we prepare 4 functions.</p><ul><li><em>getPosts</em></li><li><em>getPost</em></li><li><em>insertPost</em></li><li><em>updatePost</em></li><li><em>deletePost</em></li></ul><p>All these functions return a promise. And we don’t forget to export them at the end of the file.</p><h4>getPosts</h4><p>We have just to return the data array of objects, if array exists.</p><pre>function getPosts() {<br>    return new Promise((resolve, reject) =&gt; {<br>        if (posts.length === 0) {<br>            reject({<br>                message: &#39;no posts available&#39;,<br>                status: 202<br>            })<br>        }</pre><pre>        resolve(posts)<br>    })<br>}</pre><p>We return a promise.</p><ul><li>If no posts, display a custom message (<strong><em>reject</em></strong><em>,</em><strong> 202 </strong>⚠️).</li><li>If posts, diplay array posts (<strong><em>resolve</em></strong><em>,</em> <strong>200 </strong>👌).</li></ul><h4>getPost</h4><p>Like the previous function, except, we want return an object instead an array. For that, we will use the native JavaScript function <em>find()</em> for retrieve the object by id in parameter of the function.</p><pre>function getPost(id) {<br>    return new Promise((resolve, reject) =&gt; {<br>        helper.mustBeInArray(posts, id)<br>        .then(post =&gt; resolve(post))<br>        .catch(err =&gt; reject(err))<br>    })<br>}</pre><p>We return a promise.</p><ul><li>If not post with this id, display an error message (<strong><em>reject</em></strong>, <strong>404 </strong>⚠️).</li><li>If post, display array posts (<strong><em>resolve</em></strong>, <strong>200 </strong>👌).</li></ul><h4>insertPost</h4><p>We will insert a new row.</p><pre>function insertPost(newPost) {<br>    return new Promise((resolve, reject) =&gt; {<br>        const id = { id: helper.getNewId(posts) }<br>        const date = { <br>            createdAt: helper.newDate(),<br>            updatedAt: helper.newDate()<br>        } <br>        newPost = { ...id, ...date, ...newPost }<br>        posts.push(newPost)<br>        helper.writeJSONFile(filename, posts)<br>        resolve(newPost)<br>    })<br>}</pre><p>We return a promise.</p><ul><li>If post, display array posts (<strong><em>resolve</em></strong>, <strong>200 </strong>👌).</li></ul><h4>updatePost</h4><p>We will use the native JavaScript function <em>find()</em> for retrieve the object by id in parameter of the function. Like adding a post, we have some content from the client. Then we find the index of the row via the native function findIndex. In this row, we add the id, the updated date and the content.</p><pre>function updatePost(id, newPost) {<br>    return new Promise((resolve, reject) =&gt; {<br>        helper.mustBeInArray(posts, id)<br>        .then(post =&gt; {<br>            const index = posts.findIndex(p =&gt; p.id == post.id)<br>            id = { id: post.id }<br>            const date = {<br>                createdAt: post.createdAt,<br>                updatedAt: helper.newDate()<br>            } <br>            posts[index] = { ...id, ...date, ...newPost }<br>            helper.writeJSONFile(filename, posts)<br>            resolve(posts[index])<br>        })<br>        .catch(err =&gt; reject(err))<br>    })<br>}</pre><p>We return a promise.</p><ul><li>If no post with this id, display an error message (<strong><em>reject</em></strong><em>,</em> <strong>404 </strong>⚠️).</li><li>If post, display array posts (<strong><em>resolve</em></strong>, <strong>200 </strong>👌).</li></ul><h4>deletePost</h4><p>For that, we will use the native JavaScript function <em>find()</em> for retreive the object by id in parameter of the function. After checking if the id is an integer and the row exists in the array, we delete via the native function <em>filter()</em>.</p><pre>function deletePost(id) {<br>    return new Promise((resolve, reject) =&gt; {<br>        helper.mustBeInArray(posts, id)<br>        .then(() =&gt; {<br>            posts = posts.filter(p =&gt; p.id !== id)<br>            helper.writeJSONFile(filename, posts)<br>            resolve()<br>        })<br>        .catch(err =&gt; reject(err))<br>    })<br>}</pre><p>We return a promise.</p><ul><li>If not post with this id, display an error message (<strong><em>reject</em></strong>, <strong>404 </strong>⚠️)</li><li>If post, diplay array posts (<strong><em>resolve</em></strong>, <strong>200 </strong>👌)</li></ul><h3>Routes</h3><p>Open the <strong>index.routes.js</strong> file for declaring the route “/api/v1/posts”.</p><pre>const express = require(&#39;express&#39;)<br>const router = express.Router()<br>module.exports = router</pre><pre>router.use(&#39;/api/v1/posts&#39;, require(&#39;./post.routes&#39;))</pre><p>Then in the <strong>index.js</strong> root file for loading the previous file.</p><pre>const app = express()<br>app.use(morgan(&#39;tiny&#39;))<br>app.use(express.json())<br>app.use(express.urlencoded({ extended: true }))<br>app.use(require(&#39;./routes/index.routes&#39;))</pre><p>And now, we can work in the <strong>post.routes.js</strong> file.</p><pre>const express = require(&#39;express&#39;)<br>const router = express.Router()<br>const post = require(&#39;../models/post.model&#39;)<br>const m = require(&#39;../helpers/middlewares&#39;)<br>// Routes<br>module.exports = router</pre><h4>All posts</h4><pre>/* All posts */<br>router.get(&#39;/&#39;, async (req, res) =&gt; {<br>    await post.getPosts()<br>    .then(posts =&gt; res.json(posts))<br>    .catch(err =&gt; {<br>        if (err.status) {<br>            res.status(err.status).json({ message: err.message })<br>        } else {<br>            res.status(500).json({ message: err.message })<br>        }<br>    })<br>})</pre><p>CURL request (200)</p><pre>curl -i -X GET <a href="http://localhost:1337/api/v1/posts">http://localhost:1337/api/v1/posts</a></pre><h4>A post by id</h4><pre>/* A post by id */<br>router.get(&#39;/:id&#39;, m.mustBeInteger, async (req, res) =&gt; {<br>    const id = req.params.id</pre><pre>    await post.getPost(id)<br>    .then(post =&gt; res.json(post))<br>    .catch(err =&gt; {<br>        if (err.status) {<br>            res.status(err.status).json({ message: err.message })<br>        } else {<br>            res.status(500).json({ message: err.message })<br>        }<br>    })<br>})</pre><p>CURL request (200, 404, 400).</p><pre>curl -i -X GET <a href="http://localhost:1337/api/v1/posts">http://localhost:1337/api/v1/posts/1</a><br>curl -i -X GET <a href="http://localhost:1337/api/v1/posts">http://localhost:1337/api/v1/posts/404</a><br>curl -i -X GET <a href="http://localhost:1337/api/v1/posts">http://localhost:1337/api/v1/posts/string</a></pre><h4>Insert a new post</h4><pre>/* Insert a new post */<br>router.post(&#39;/&#39;, m.checkFieldsPost, async (req, res) =&gt; {<br>    await post.insertPost(req.body)<br>    .then(post =&gt; res.status(201).json({<br>        message: `The post #${post.id} has been created`,<br>        content: post<br>    }))<br>    .catch(err =&gt; res.status(500).json({ message: err.message }))<br>})</pre><p>CURL requests (201, 400).</p><pre>curl -i -X POST \<br>    -H &quot;Content-Type: application/json&quot; \<br>    -d &#39;{ &quot;title&quot;: &quot;test again&quot;, &quot;content&quot;: &quot;Lorem Ipsum&quot;, &quot;tags&quot;: [&quot;tag1&quot;, &quot;tag4&quot;] }&#39; \<br>    <a href="http://localhost:1337/api/v1/posts">http://localhost:1337/api/v1/posts</a></pre><pre>curl -i -X POST \<br>  <a href="http://localhost:1337/api/v1/posts">http://localhost:1337/api/v1/posts</a></pre><h4>Update a post</h4><pre>/* Update a post */<br>router.put(&#39;/:id&#39;, m.mustBeInteger, m.checkFieldsPost, async (req, res) =&gt; {<br>    const id = req.params.id</pre><pre>    await post.updatePost(id, req.body)<br>    .then(post =&gt; res.json({<br>        message: `The post #${id} has been updated`,<br>        content: post<br>    }))<br>    .catch(err =&gt; {<br>        if (err.status) {<br>            res.status(err.status).json({ message: err.message })<br>        }<br>        res.status(500).json({ message: err.message })<br>    })<br>})</pre><p>CURL requests (200, 404 , 400, 400).</p><pre>curl -i -X PUT \<br>    -H &quot;Content-Type: application/json&quot; \<br>    -d &#39;{ &quot;title&quot;: &quot;The first&quot;, &quot;content&quot;: &quot;Lorem Ipsum 2&quot;, &quot;tags&quot;: [&quot;tag1&quot;, &quot;tag4&quot;] }&#39; \<br>    <a href="http://localhost:1337/api/v1/posts/1">http://localhost:1337/api/v1/posts/1</a></pre><pre>curl -i -X PUT \<br>    -H &quot;Content-Type: application/json&quot; \<br>    -d &#39;{ &quot;title&quot;: &quot;The first&quot;, &quot;content&quot;: &quot;Lorem Ipsum 2&quot;, &quot;tags&quot;: [&quot;tag1&quot;, &quot;tag4&quot;] }&#39; \<br>    <a href="http://localhost:1337/api/v1/posts/1">http://localhost:1337/api/v1/posts/404</a></pre><pre>curl -i -X PUT  <a href="http://localhost:1337/api/v1/posts/2">http://localhost:1337/api/v1/posts/1</a><br>curl -i -X PUT  <a href="http://localhost:1337/api/v1/posts/1">http://localhost:1337/api/v1/posts/string</a></pre><h4>Delete a post</h4><pre>/* Delete a post */<br>router.delete(&#39;/:id&#39;, m.mustBeInteger, async (req, res) =&gt; {<br>    const id = req.params.id<br>    <br>    await post.deletePost(id)<br>    .then(post =&gt; res.json({<br>        message: `The post #${id} has been deleted`<br>    }))<br>    .catch(err =&gt; {<br>        if (err.status) {<br>            res.status(err.status).json({ message: err.message })<br>        }<br>        res.status(500).json({ message: err.message })<br>    })<br>})</pre><p>CURL requests (200, 404, 400).</p><pre>curl -i -X DELETE <a href="http://localhost:1337/api/v1/posts/3">http://localhost:1337/api/v1/posts/</a>1<br>curl -i -X DELETE <a href="http://localhost:1337/api/v1/posts/3">http://localhost:1337/api/v1/posts/404</a><br>curl -i -X DELETE <a href="http://localhost:1337/api/v1/posts/3">http://localhost:1337/api/v1/posts/string</a></pre><h3>Conclusion</h3><p>After made fun with Promises, build his own API RESTfull without Database still limited. In our case, if we want adding some authors. How to make the relationship ? This is more simple with a real database. You can switch to Database easily with modify the model file.</p><p>For a better API, you can use the <a href="https://github.com/hapijs/joi">Joi</a> package to check your model schema and using this <a href="https://github.com/expressjs/cors">middleware</a> for enabling the CORS.</p><p>And yes, this API is available on <a href="https://github.com/EtienneR/api_express_no_db">Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b030c687e2ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Play databases with Adminer and Docker]]></title>
            <link>https://medium.com/@etiennerouzeaud/play-databases-with-adminer-and-docker-53dc7789f35f?source=rss-fd941f66a978------2</link>
            <guid isPermaLink="false">https://medium.com/p/53dc7789f35f</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Etienne Rouzeaud]]></dc:creator>
            <pubDate>Wed, 14 Feb 2018 14:25:08 GMT</pubDate>
            <atom:updated>2019-05-19T13:43:17.755Z</atom:updated>
            <content:encoded><![CDATA[<p>When you use Docker with a database you need a client to operate on it. A simple and clean solution is to install a client in a Docker container. With that, no need to install anything on your computer besides Docker. Many clients exists, like PHPMyAdmin, but we want one that can connect to different database, not just MySQL/MariaDB.<br>Adminer seems a good choice.</p><p>The prerequisites for this article is to have Docker and Docker Compose installed.</p><pre>$ docker version &amp;&amp; docker-compose version</pre><p>Versions used in this article :</p><ul><li>Docker : 17.12.0-ce ;</li><li>Docker Compose : 1.17.0 ;</li><li>Adminer : 4.5.0 ;</li><li>Postgres : 10 ;</li><li>MySQL : 8.0.3 ;</li><li>MongoDB : 3.6.2</li></ul><h3>Install Adminer</h3><p>Create a file “docker-compose.yml” in your project directory.</p><pre>version: &#39;3.1&#39;</pre><pre>   services:</pre><pre>       adminer:</pre><pre>           image: dockette/adminer:full-php5</pre><pre>           restart: always</pre><pre>           ports:</pre><pre>              - 8080:8080</pre><p>Some explanations :</p><ul><li>“dockette/adminer:full-php5” is an unofficial image working with PHP 5 instead of PHP 7 ;</li><li>“restart” the container will be restart each time when the Docker service will be up ;</li><li>“8080” on the left side is the external port. If this port is already using you should change it ;</li><li>“8080” on the right side is the internal port. Please don’t change !</li></ul><p>Why don’t we use the official Adminer image ? You can use it, but it will not works with Mongo and PHP7.</p><blockquote>&gt; <a href="https://hub.docker.com/_/adminer">https://hub.docker.com/_/adminer</a></blockquote><blockquote>The following drivers are not supported by this image:</blockquote><blockquote>MongoDB (The driver is not supported by PHP 7)</blockquote><p>You can run this container with the command</p><pre>$ docker-compose up</pre><p>(make sure your are in the same root of the “docker-compose.yml”). If the container is up, you can connect to <a href="http://localhost:8080/">http://localhost:8080</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bKHt88QCAjMFDgUyIdhPZg.png" /></figure><p>Working but we don’t have database server yet.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl41YfdYdptDB9RHIA%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl41YfdYdptDB9RHIA%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl41YfdYdptDB9RHIA%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="239" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce7cb2fef1a33779adaf5877af17acc1/href">https://medium.com/media/ce7cb2fef1a33779adaf5877af17acc1/href</a></iframe><h3>Postgres</h3><h4>Prepare the server</h4><p>In the same file (in the “services” column).</p><pre>dbPostgres:</pre><pre>    image: postgres:10</pre><pre>    restart: always</pre><pre>    ports:</pre><pre>        - 5432:5432</pre><pre>    environment:</pre><pre>        POSTGRES_USER: root</pre><pre>        POSTGRES_PASSWORD: changeme</pre><pre>        POSTGRES_DB: mydb</pre><p>Some explanations :</p><ul><li>“postgres:10” is the official image of the 10 version ;</li><li>“restart: always” means restart the service each time the Docker daemon is restarted ;</li><li>“5432” (on the left side) is the external port. If this port is already using you should change it ;</li><li>“5432” (on the right side) is the internal port. Please don’t change it!</li><li>“POSTGRES_USER” is the login ;</li><li>“POSTGRES_PASSWORD” is the password ;</li><li>“POSTGRES_DB” is the name of the database.</li></ul><p>If the Adminer container is still running, stop it with CTRL-C and then run</p><pre>$ docker-compose up</pre><h4>Connection with Adminer and Postgres</h4><p>Go back in Adminer (http://localhost:8080). Then complete the form :</p><ul><li>“System” : select “PostgresSQL” ;</li><li>“Server” : type “dbPostgres” ;</li><li>“Username” : type “root” ;</li><li>“Password” : type “changeme” ;</li><li>“Database” : type “mydb” ;</li><li>Click “login” button.</li></ul><h3>MySQL</h3><h4>Prepare the server</h4><p>In the same file (in the “services” column).</p><pre>dbMysql:</pre><pre>    image: mysql:8.0.3</pre><pre>    restart: always</pre><pre>    environment:</pre><pre>        MYSQL_ROOT_PASSWORD: changeme</pre><pre>        MYSQL_DATABASE: mydb</pre><p>Some explanations :</p><ul><li>“mysql:8.0.3” is the official image of the 8.0.3 version (or “mariadb” in you want to use MariaDB) ;</li><li>“restart: always” means restart the service each time the Docker daemon is restarted ;</li><li>“3306” (on the left side) is the external port. If this port is already using you should change it ;</li><li>“3306” (on the right side) is the internal port. Please don’t change it!</li><li>“MYSQL_ROOT_PASSWORD” is the password ;</li><li>“MYSQL_DATABASE” is the name of the database.</li></ul><p>With MySQL you can choose a simple user with `MYSQL_USER` and`MYSQL_PASSWORD`.</p><p>If the Adminer container is still running, stop it with CTRL-C and then run</p><pre>$ docker-compose up</pre><h4>Connection with Adminer and MySQL</h4><p>Go back in Adminer (http://localhost:8080). Then complete the form :</p><ul><li>“System” : select “MySQL” ;</li><li>“Server” : type “dbMysql” ;</li><li>“Username” : type “root” ;</li><li>“Password” : type “changeme” ;</li><li>“Database” : type “mydb” ;</li><li>Click “login” button.</li></ul><h3>MongoDB</h3><p>In the same file (in the “services” column).</p><pre>dbMongo:</pre><pre>    image: mongo:3.6.2</pre><pre>    restart: always</pre><pre>    ports:</pre><pre>        - 27017:27017</pre><pre>    environment:</pre><pre>        MONGO_INITDB_ROOT_USERNAME: root</pre><pre>        MONGO_INITDB_ROOT_PASSWORD: changeme</pre><p>Some explanations :</p><ul><li>“mongo:3.6.2” is the official image of the 3.6.2 version ;</li><li>“restart: always” means restart the service each time the Docker daemon is restarted ;</li><li>“27017” (on the left side) is the external port. If this port is already using you should change it ;</li><li>“27017” (on the right side) is the internal port. Please don’t change it!</li><li>“MONGO_INITDB_ROOT_USERNAME” : is the login ;</li><li>“MONGO_INITDB_ROOT_PASSWORD” is the password root.</li></ul><p>If the Adminer container is still running, stop it with CTRL-C and then run</p><pre>$ docker-compose up</pre><h4>Connection with Adminer and MongoDB</h4><p>Go back in Adminer (http://localhost:8080). Then complete the form :</p><ul><li>“System” : select “Mongo” ;</li><li>“Server” : type “dbMongo” ;</li><li>“Username” : type “root” ;</li><li>“Password” : type “changeme” ;</li><li>“Database” : leave empty ;</li><li>Click “login” button.</li></ul><h3>Global file</h3><pre>version: &#39;3.1&#39;</pre><pre>    services:</pre><pre>        adminer:</pre><pre>            image: dockette/adminer:full-php5</pre><pre>            restart: always</pre><pre>            ports:</pre><pre>                - 8080:8080</pre><pre>        dbPostgres:</pre><pre>            image: postgres:10</pre><pre>            restart: always</pre><pre>            ports:</pre><pre>                - 5432:5432</pre><pre>            environment:</pre><pre>                POSTGRES_USER: root</pre><pre>                POSTGRES_PASSWORD: changeme</pre><pre>                POSTGRES_DB: mydb<br>        dbMysql:</pre><pre>            image: mysql:8.0.3</pre><pre>            restart: always</pre><pre>            ports:</pre><pre>                - 3306:3306</pre><pre>            environment:</pre><pre>                MYSQL_ROOT_PASSWORD: changeme</pre><pre>                MYSQL_DATABASE: mydb</pre><pre>        dbMongo:</pre><pre>            image: mongo:3.6.2</pre><pre>            restart: always</pre><pre>            ports:</pre><pre>                - 27017:27017</pre><pre>            environment:</pre><pre>                MONGO_INITDB_ROOT_USERNAME: root</pre><pre>                MONGO_INITDB_ROOT_PASSWORD: changeme</pre><h3>Sources</h3><ul><li>Official Adminer website : <a href="https://www.adminer.org/">https://www.adminer.org</a></li><li>Adminer demo : <a href="https://adminer.sourceforge.io/editor.php">https://adminer.sourceforge.io/editor.php</a></li><li>Official Adminer image : <a href="https://hub.docker.com/_/adminer">https://hub.docker.com/_/adminer</a></li><li>Unofficial Adminer image : <a href="https://hub.docker.com/r/dockette/adminer">https://hub.docker.com/r/dockette/adminer</a></li><li>Official Postgres image : <a href="https://hub.docker.com/_/postgres">https://hub.docker.com/_/postgres</a></li><li>Official MySQL image : <a href="https://hub.docker.com/_/mysql">https://hub.docker.com/_/mysql</a></li><li>Official MariaDB image : <a href="https://hub.docker.com/_/mariadb">https://hub.docker.com/_/mariadb</a></li><li>Official MongoDB image : <a href="https://hub.docker.com/_/mongo">https://hub.docker.com/_/mongo</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53dc7789f35f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang : string to array string]]></title>
            <link>https://medium.com/@etiennerouzeaud/golang-string-to-array-string-dacc6b78a92e?source=rss-fd941f66a978------2</link>
            <guid isPermaLink="false">https://medium.com/p/dacc6b78a92e</guid>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Etienne Rouzeaud]]></dc:creator>
            <pubDate>Sun, 26 Feb 2017 14:01:14 GMT</pubDate>
            <atom:updated>2017-02-26T14:01:14.680Z</atom:updated>
            <content:encoded><![CDATA[<p>When you use database like MySQL, MariaDB or SQLite, you can’t use array fields unlike in Postgres or MongoDB. To get tags for example, you use a string field with each tag separate by a comma or semicolon. But you will need to put these values into an array…</p><p>In this example, we are going to use a simple structure with :</p><ul><li><strong>Id</strong> (<em>int</em>) ;</li><li><strong>Title</strong> (<em>string</em>) ;</li><li><strong>Tags</strong> (<em>string</em>) empty or not, separate by commas ;</li><li><strong>TagsSplit</strong> (<em>string array</em>) empty by default.</li></ul><p>In a first time, we are going to declare this structure and put in the last field (<strong>TagsSplit</strong>) of our tags (<strong>Tags</strong>). Then in a second time, we are going to put in place a HTTP Server and display result in HTML.</p><h3>String to array string</h3><h4>Structure</h4><p>As say before, we are going to use a simple structure like below.</p><pre>type Article struct {<br>    Id          int<br>    Title       string<br>    Tags        string<br>    TagsSplit   []string<br>}</pre><h4>For many articles</h4><p>Let’s create 3 articles with tags separated by commas excepted the last.</p><pre>var articles = []Article{<br>    Article{<br>        Id:    1,<br>        Title: &quot;My First Article&quot;,<br>        Tags:  &quot;golang,mongo&quot;,<br>    },<br>    Article{<br>        Id:    2,<br>        Title: &quot;My Second Article&quot;,<br>        Tags:  &quot;php,sql&quot;,<br>    },<br>    Article{<br>        Id:    3,<br>        Title: &quot;My Third Article&quot;,<br>    },<br>}</pre><p>And result display.</p><pre>func main() {<br>    fmt.Println(articles)<br>}</pre><p>You will get a result like this array.</p><p>[{1 My First Article sql,golang []} {2 My Secod Article php,mongo []} {3 My Third Article []}]</p><p>So now, we are going to use the field <strong>TagsSplit</strong> unused.<br>Just after the <strong>articles</strong> variable declaration and before display the result, add this loop <strong>range</strong>.</p><pre>for i, article := range articles {<br>    tags := strings.Split(article.Tags, &quot;,&quot;)<br>    articles[i].TagsSplit = make([]string, len(tags))<br>    articles[i].TagsSplit = tags</pre><pre>    // Don&#39;t use &#39;append&#39; function :<br>    // articles[i].TagsSplit = append(articles[i].TagsSplit, tags...)<br>}</pre><p>Don’t forget to import the native “strings” library into “import”.</p><p>In each row, we split tags by comma and push the “TagExplode” field with the append function. Like this, we got the new array result with array tags.</p><p>[{1 My First Article golang,mongo []} {2 My Second Article php,sql [php sql]} {3 My Third Article []}]</p><h4>For an article</h4><p>For an article, we don’t need to loop because it’s a single row defined.</p><pre>articles[1].TagsSplit = strings.Split(articles[1].Tags, &quot;,&quot;)<br>fmt.Println(articles[1])</pre><p>Same result but just a single row.</p><p>{2 My Second Article php,sql [php sql]}</p><h4>Create a function</h4><p>We can add a function for less code.</p><pre>func main() {<br>    for i, article := range articles {<br>        tags := splitTags(article.Tags)<br>        articles[i].TagsSplit = make([]string, len(tags))<br>        articles[i].TagsSplit = tags<br>    }</pre><pre>    fmt.Println(articles)</pre><pre>    articles[1].TagsSplit = splitTags(articles[1].Tags)<br>    fmt.Println(articles[1])<br>}</pre><pre>func splitTags(article string) []string {<br>    tags := strings.Split(article, &quot;,&quot;)</pre><pre>    return tags<br>}</pre><p>Same result :)</p><p>Test this code <a href="https://play.golang.org/p/ESwdM3j6og">Go Playground</a>.</p><h3>HTML rendering</h3><p>Being a lazy developper, I prefer using Gin as server MUX instead of the native HTTP server.</p><h4>HTTP Server</h4><p>Same example but we use an HTTP server for display results in the “main.go” file.</p><pre>package main</pre><pre>import (<br>    &quot;strconv&quot;<br>    &quot;strings&quot;</pre><pre>    &quot;github.com/gin-gonic/gin&quot; // got get github.com/gin-gonic/gin<br>)</pre><pre>type Article struct {<br>    Id        int<br>    Title     string<br>    Tags      string<br>    TagsSplit []string<br>}</pre><pre>var articles = []Article{<br>    Article{<br>        Id:    1,<br>        Title: &quot;My First Article&quot;,<br>        Tags:  &quot;golang,mongo&quot;,<br>    },<br>    Article{<br>        Id:    2,<br>        Title: &quot;My Second Article&quot;,<br>        Tags:  &quot;php,sql,docker&quot;,<br>    },<br>    Article{<br>        Id:    3,<br>        Title: &quot;My Third Article&quot;,<br>    },<br>}</pre><pre>func main() {<br>    r := gin.Default()</pre><pre>    r.LoadHTMLGlob(&quot;views/*&quot;)</pre><pre>    r.GET(&quot;/&quot;, articlesHandler)<br>    r.GET(&quot;/:id&quot;, articleHandler)</pre><pre>    r.Run(&quot;:3000&quot;)<br>}</pre><pre>func articlesHandler(c *gin.Context) {<br>    c.HTML(200, &quot;view_articles.html&quot;, gin.H{<br>        &quot;Articles&quot;: getTagByArticles(articles),<br>    })<br>}</pre><pre>func articleHandler(c *gin.Context) {<br>    id, _ := strconv.Atoi(c.Params.ByName(&quot;id&quot;))<br>    index := id - 1</pre><pre>    if index &lt; len(articles) {<br>        c.HTML(200, &quot;view_article.html&quot;, gin.H{<br>            &quot;Article&quot;: getTagByArticle(articles[index]),<br>        })</pre><pre>    } else {<br>        c.JSON(404, gin.H{&quot;error&quot;: &quot;This article doesn&#39;t exists&quot;})<br>    }<br>}</pre><pre>func getTagByArticles(article []Article) interface{} {<br>    for i, _ := range articles {<br>        tags := splitTags(articles[i].Tags)<br>        articles[i].TagsSplit = make([]string, len(tags))<br>        articles[i].TagsSplit = tags<br>    }</pre><pre>    return articles<br>}</pre><pre>func getTagByArticle(article Article) interface{} {<br>    article.TagsSplit = splitTags(article.Tags)</pre><pre>    return article<br>}</pre><pre>func splitTags(article string) []string {<br>    tags := strings.Split(article, &quot;,&quot;)</pre><pre>    return tags<br>}</pre><h4>HTML files</h4><p>Create a folder named “views” with 2 files inside.</p><ul><li>view_articles.html</li><li>view_article.html</li></ul><h4>All articles (view_articles.html)</h4><p>We use 2 loops (range) for all articles and all tags in each article.</p><pre>&lt;!-- views/view_articles.html --&gt;</pre><pre>&lt;section&gt;<br>{{ if $articles }}<br>    {{ range $index, $article := .Articles }}<br>    &lt;article&gt;<br>        &lt;h2&gt;&lt;a href=&quot;{{ $article.Id }}&quot;&gt;{{ $article.Title }}&lt;/a&gt;&lt;/h2&gt;<br>        {{ if $article.Tags }}<br>        &lt;ul&gt;<br>        {{ range $tag := $article.TagsSplit }}<br>            &lt;li&gt;{{ $tag }}&lt;/li&gt;<br>        {{ end }}<br>        &lt;/ul&gt;<br>        {{ end }}<br>    &lt;/article&gt;<br>{{ end }}<br>&lt;/section&gt;</pre><h4>One article (view_article.html)</h4><p>We use just one loop (range) for all tags include in the article.</p><pre>&lt;!-- views/view_article.html --&gt;</pre><pre>&lt;article&gt;<br>    &lt;h1&gt;{{ .Article.Title }}&lt;/h1&gt;<br>    {{ if .Article.Tags }}<br>    &lt;ul&gt;<br>    {{ range $tag := .Article.TagsSplit }}<br>        &lt;li&gt;{{ $tag }}&lt;/li&gt;<br>    {{ end }}<br>    &lt;/ul&gt;<br>    {{ end }}<br>&lt;/article&gt;</pre><pre>&lt;a href=&quot;/&quot;&gt;Back to the list&lt;/a&gt;</pre><h3>Conclusion</h3><p>This method works… Of course, if you have another solution, please share it :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dacc6b78a92e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang YAML to JSON with Gin]]></title>
            <link>https://medium.com/@etiennerouzeaud/golang-yaml-to-json-with-gin-e2e1529274b1?source=rss-fd941f66a978------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2e1529274b1</guid>
            <category><![CDATA[gin]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[yaml]]></category>
            <dc:creator><![CDATA[Etienne Rouzeaud]]></dc:creator>
            <pubDate>Sun, 20 Nov 2016 14:03:49 GMT</pubDate>
            <atom:updated>2017-04-06T09:14:03.590Z</atom:updated>
            <content:encoded><![CDATA[<p>You have a YAML file and you want to display these informations in a HTTP API with a JSON result. So you need to read the file then binding YAML datas (keys and values) and display to JSON.</p><h3>What do we need ?</h3><p>We need a micro framework and to bind YAML, Gin and YAML.</p><pre>go get gopkg.in/gin-gonic/gin.v1 &amp;&amp; go get gopkg.in/yaml.v2</pre><h3>The YAML file</h3><p>Create the YAML file named “config.yml”.</p><pre>&#39;title&#39;: &#39;My first article&#39;<br>&#39;email&#39;: <a href="/service/mailto:go@email.com">&#39;go@email.com&#39;</a><br>&#39;tags&#39;: [go, golang, yaml, json]</pre><p>So, keys are “title”, “email” and “tags” (the last is a string array).</p><h3>The script</h3><p>Create a “main.go” file.</p><pre>package main</pre><pre>import (<br> &quot;log&quot;<br> &quot;io/ioutil&quot;</pre><pre> &quot;gopkg.in/gin-gonic/gin.v1&quot;<br> &quot;gopkg.in/yaml.v2&quot;<br>)</pre><pre>type Config struct {<br> Title string `json:&quot;title&quot;`<br> Email string `json:&quot;email&quot;`<br> Tags []string `json:&quot;tags&quot;`<br>}</pre><pre>func main() {<br> r := gin.Default()</pre><pre> r.GET(&quot;&quot;, func(c *gin.Context) {<br>  // The next<br> })</pre><pre> r.Run(&quot;:3000&quot;)<br>}</pre><p>As you can see, we load libraries then we declare a struct named “Config” with our 3 keys present in the YAML file.</p><h4>Load the YAML file</h4><p>For loading the file, we use the native function “ReadFile” from “ioutil”.</p><pre>data, err := ioutil.ReadFile(&quot;config.yml&quot;)<br>if err != nil {<br> log.Fatalf(&quot;error: %v&quot;, err)<br>}</pre><h4>Binding YAML datas</h4><p>We gonna use the “Unmarshal” function from “Yaml” library.</p><pre>var config Config<br>err = yaml.Unmarshal([]byte(data), &amp;config)<br>if err != nil {<br> log.Fatalf(&quot;error: %v&quot;, err)<br>}</pre><p>And we put these datas in a new var “result”.</p><pre>result := Config{<br> Title: config.Title,<br> Email: config.Email,<br> Tags: config.Tags,<br>}</pre><h4>Display JSON result</h4><p>With Gin it’s very simple, we just need to use the “c.JSON” function.</p><pre>c.JSON(200, result)</pre><h3>Result &amp; final code</h3><p>After starting the server, you will get a JSON result.</p><pre>{&quot;title&quot;:&quot;This is my go blog&quot;,&quot;email&quot;:<a href="/service/mailto:go@email.com">&quot;go@email.com</a>&quot;,&quot;tags&quot;:[&quot;go&quot;,&quot;golang&quot;,&quot;yaml&quot;,&quot;json&quot;]}</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8b52ff7a068226c208955165178c5c9/href">https://medium.com/media/f8b52ff7a068226c208955165178c5c9/href</a></iframe><h3>Sources</h3><p>- Gin : <a href="https://github.com/gin-gonic/gin">https://github.com/gin-gonic/gin</a><br>- YAML : <a href="https://github.com/go-yaml/yaml">https://github.com/go-yaml/yaml</a><br>- YAML Lint : <a href="http://www.yamllint.com/">http://www.yamllint.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2e1529274b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple CRUD application with Javascript]]></title>
            <link>https://medium.com/@etiennerouzeaud/a-simple-crud-application-with-javascript-ebc82f688c59?source=rss-fd941f66a978------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebc82f688c59</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Etienne Rouzeaud]]></dc:creator>
            <pubDate>Fri, 06 May 2016 10:30:49 GMT</pubDate>
            <atom:updated>2016-05-08T20:34:59.006Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s make a basic application without JS framework to display a simple list of countries. Then we will should make classics actions like add, edit or delete a country without reload the page as a Single Page Application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*1wurG2eFZQCyC9mxfuJBSQ.gif" /><figcaption>Not the best CSS..</figcaption></figure><p>For that, we gonna use a global function were we need :</p><ul><li>“el” : the div element ;</li><li>“countries” : rows in an array ;</li><li>“Count” : number of rows ;</li><li>“FetchAll” : select all rows ;</li><li>“Add” : add a new row ;</li><li>“Edit” : edit a row ;</li><li>“Delete” : delete a row.</li></ul><h3>First step : read and count</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F2FazoPKdiLJFJxbe8%2Ftwitter%2Fiframe&amp;src_secure=1&amp;url=http%3A%2F%2Fgiphy.com%2Fgifs%2Fcheezburger-running-goat-squee-2FazoPKdiLJFJxbe8&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F2FazoPKdiLJFJxbe8%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/37ea32874aef8e50fed3edae4c7d0c0e/href">https://medium.com/media/37ea32874aef8e50fed3edae4c7d0c0e/href</a></iframe><p>The HTML code with the counter and the table.</p><pre>&lt;p id=&quot;counter&quot;&gt;&lt;/p&gt;</pre><pre>&lt;table&gt;<br> &lt;tr&gt;<br>   &lt;th&gt;Name&lt;/th&gt;<br> &lt;/tr&gt;<br> &lt;tbody id=&quot;countries&quot;&gt;<br> &lt;/tbody&gt;<br>&lt;/table&gt;</pre><p>In the Javascript code, we declare a global function “app()”.</p><pre>var app = new function() {</pre><pre> // Code</pre><pre>}</pre><p>We select our element where we want to display data (“#countries”).</p><pre>this.el = document.getElementById(&#39;countries&#39;);</pre><p>Then our data in a simple array.</p><pre>this.countries = [&#39;France&#39;, &#39;Germany&#39;, &#39;England&#39;, &#39;Spain&#39;, &#39;Belgium&#39;, &#39;Italy&#39;, &#39;Portugal&#39;, &#39;Irland&#39;, &#39;Luxembourg&#39;];</pre><p>And the counter in a the function “Count()”.</p><pre>this.Count = function(data) {<br> var el = document.getElementById(&#39;counter&#39;);<br> var name = &#39;country&#39;;</pre><pre> if (data) {<br>  if (data &gt; 1) {<br>   name = &#39;countries&#39;;<br>  }<br>  el.innerHTML = data + &#39; &#39; + name ;<br> } else {<br>  el.innerHTML = &#39;No &#39; + name;<br> }<br>};</pre><p>With these 3 informations, we can start our CRUD method in a new function “FetchAll()” .</p><pre>this.FetchAll = function() {<br> var data = &#39;&#39;;</pre><pre> if (this.countries.length &gt; 0) {<br>  for (i = 0; i &lt; this.countries.length; i++) {<br>   data += &#39;&lt;tr&gt;&#39;;<br>   data += &#39;&lt;td&gt;&#39; + this.countries[i] + &#39;&lt;/td&gt;&#39;;<br>   data += &#39;&lt;/tr&gt;&#39;;<br>  }<br> }<br> <br> this.Count(this.countries.length);<br> return this.el.innerHTML = data;<br>};</pre><p>We can test our code with calling the “FetchAll()” function outside the mother function “app()”.</p><pre>app.FetchAll();</pre><h3>Second step : add a row with push</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FvmYVP9uCg6VW0%2Ftwitter%2Fiframe&amp;src_secure=1&amp;url=http%3A%2F%2Fgiphy.com%2Fgifs%2FvmYVP9uCg6VW0&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FvmYVP9uCg6VW0%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="254" frameborder="0" scrolling="no"><a href="https://medium.com/media/16179e759141e95fcd4d9d99f9e56ea1/href">https://medium.com/media/16179e759141e95fcd4d9d99f9e56ea1/href</a></iframe><p>Add an input field in the HTML code.</p><pre>&lt;form action=&quot;javascript:void(0);&quot; method=&quot;POST&quot; onsubmit=&quot;app.Add()&quot;&gt; <br> &lt;input type=&quot;text&quot; id=&quot;add-name&quot; placeholder=&quot;New country&quot;&gt;<br> &lt;input type=&quot;submit&quot; value=&quot;Add&quot;&gt;<br>&lt;/form&gt;</pre><p>And in the global function “app”, add the “Add” function :</p><pre>this.Add = function () {<br> alert(&#39;add something&#39;);<br>}</pre><p>Ok, we need to get value from the “#add-name” element, push it in the array “countries” and display the new list without reloading the page…</p><pre>this.Add = function () {<br> el = document.getElementById(&#39;add-name&#39;);<br> // Get the value<br> var country = el.value;</pre><pre> if (country) {<br>  // Add the new value<br>  this.countries.push(country.trim());<br>  // Reset input value<br>  el.value = &#39;&#39;;<br>  // Dislay the new list<br>  this.FetchAll();<br> }<br>};</pre><h3>Third step : edit a row with splice</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fce1Iv4qbuFlZK%2Ftwitter%2Fiframe&amp;src_secure=1&amp;url=http%3A%2F%2Fgiphy.com%2Fgifs%2Ftable-transformer-expanding-ce1Iv4qbuFlZK&amp;image=http%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fce1Iv4qbuFlZK%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3f2b322f8c5258761d42bcac5ff5de4/href">https://medium.com/media/d3f2b322f8c5258761d42bcac5ff5de4/href</a></iframe><p>For edit a row, we need to create a new form and put the value in the field. This field is by default hiding.</p><pre>&lt;div id=&quot;spoiler&quot; role=&quot;aria-hidden&quot;&gt;<br> &lt;form action=&quot;javascript:void(0);&quot; method=&quot;POST&quot; id=&quot;saveEdit&quot;&gt;<br> &lt;input type=&quot;text&quot; id=&quot;edit-name&quot;&gt;<br> &lt;input type=&quot;submit&quot; value=&quot;Edit&quot; /&gt; &lt;a onclick=&quot;CloseInput()&quot; aria-label=&quot;Close&quot;&gt;&amp;#10006;&lt;/a&gt;<br> &lt;/form&gt;<br>&lt;/div&gt;</pre><p>Just a little bit of CSS…</p><pre>#spoiler{<br> display: none;<br>}</pre><p>Outside the global function, create the new function “CloseInput()”.</p><pre>function CloseInput() {<br> document.getElementById(&#39;spoiler&#39;).style.display = &#39;none&#39;;<br>}</pre><p>We need to display the button “edit” for each row. Add the line in the loop of the function “FetchAll()”.</p><pre>data += &#39;&lt;td&gt;&lt;button onclick=&quot;app.Edit(&#39; + i + &#39;)&quot;&gt;Edit&lt;/button&gt;&lt;/td&gt;&#39;;</pre><p>And in a new function “Edit(item)”.</p><pre>this.Edit = function (item) {<br> alert(item);<br>}</pre><p>Now we get the number of the row concerned, let’s play !</p><pre>this.Edit = function (item) {<br> var el = document.getElementById(&#39;edit-name&#39;);<br> // Display value in the field<br> el.value = this.countries[item];<br> // Display fields<br> document.getElementById(&#39;spoiler&#39;).style.display = &#39;block&#39;;<br> self = this;</pre><pre> document.getElementById(&#39;saveEdit&#39;).onsubmit = function() {<br>  // Get value<br>  var country = el.value;</pre><pre>  if (country) {<br>   // Edit value<br>   self.countries.splice(item, 1, country.trim());<br>   // Display the new list<br>   self.FetchAll();<br>   // Hide fields<br>   CloseInput();<br>  }<br> }<br>};</pre><h3>Fourth step : delete a row with splice</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FZVDYIE6NZaa40%2Ftwitter%2Fiframe&amp;src_secure=1&amp;url=http%3A%2F%2Fgiphy.com%2Fgifs%2Fblack-and-white-life-photography-ZVDYIE6NZaa40&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FZVDYIE6NZaa40%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="234" frameborder="0" scrolling="no"><a href="https://medium.com/media/047695915eeb1e300b0476e3e6b9b1b1/href">https://medium.com/media/047695915eeb1e300b0476e3e6b9b1b1/href</a></iframe><p>Like to edit, add this line in the loop.</p><pre>data += &#39;&lt;td&gt;&lt;button onclick=&quot;app.Delete(&#39; + i + &#39;)&quot;&gt;Delete&lt;/button&gt;&lt;/td&gt;&#39;;</pre><p>And add the function “Delete(item)”.</p><pre>this.Delete = function (item) {<br> // Delete the current row<br> this.countries.splice(item, 1);<br> // Display the new list<br> this.FetchAll();<br>};</pre><h3>Final code &amp;&amp; conclusion</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e23c42d8c7fd97f2dffec489e4bd1f24/href">https://medium.com/media/e23c42d8c7fd97f2dffec489e4bd1f24/href</a></iframe><p>This is a simple example of using data with CRUD without database using basics arrays functions like “push” and “splice”. You can use XMLHttpRequest or Fetch for calling an API. Or there are some frameworks like AngularJS, VueJS, ReactJS, EmberJS, etc… to create a SPA quickly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebc82f688c59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autoreload your Go webserver with Gulp]]></title>
            <link>https://medium.com/@etiennerouzeaud/autoreload-your-go-webserver-with-gulp-ee5e231d133d?source=rss-fd941f66a978------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee5e231d133d</guid>
            <category><![CDATA[gulp]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Etienne Rouzeaud]]></dc:creator>
            <pubDate>Thu, 17 Mar 2016 15:05:00 GMT</pubDate>
            <atom:updated>2016-03-17T15:05:00.618Z</atom:updated>
            <content:encoded><![CDATA[<h3>Auto reload your Go webserver with Gulp</h3><p>When you developp a webserver with <a href="https://golang.org/">Go</a>, you must compile each time you do an update in your code. Well.. this is redundant. With <a href="http://gulpjs.com/">Gulp</a> you can automatize this task… Indeed, when a go file is modified, a task compile the application in the “bin” folder (“gopath/bin”) then another launch the executable (the webserver).</p><p>So we have 3 distincts tasks :</p><ul><li>Application compile ;</li><li>Lauching application / server ;</li><li>Watching for files modified.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPzHpMQ7A72GtVtyD8WVsA.gif" /><figcaption>Gulpfile in action</figcaption></figure><p>Before starting, check you have <a href="https://nodejs.org/">NodeJS</a> &amp; <a href="https://www.npmjs.com/">NPM</a> installed on your machine.</p><pre>node -v &amp;&amp; npm -v </pre><p>And the environnement variable for “GOPATH” with</p><pre>go env</pre><p>If “GOPATH” is empty, set the variable environnement. More details : <a href="https://golang.org/doc/code.html#GOPATH">https://golang.org/doc/code.html#GOPATH</a></p><h3>Gulpfile</h3><p>In your application folder, create a “package.json” file.</p><pre>{<br> &quot;devDependencies&quot;: {<br> &quot;gulp&quot;: &quot;^3.8.11&quot;,<br> &quot;gulp-util&quot;: &quot;*&quot;,<br> &quot;gulp-sync&quot;: &quot;*&quot;,<br> &quot;gulp-livereload&quot;: &quot;*&quot;,<br> &quot;node-notifier&quot;: &quot;*&quot;<br> }<br>}</pre><p>Then install these modules with the command</p><pre>npm install</pre><p>Create a “Gulpfile.js” with these dependences.</p><pre>const gulp     = require(&#39;gulp&#39;),<br>      util     = require(&#39;gulp-util&#39;),<br>      notifier = require(&#39;node-notifier&#39;),<br>      sync     = require(&#39;gulp-sync&#39;)(gulp).sync,<br>      reload   = require(&#39;gulp-livereload&#39;),<br>      child    = require(&#39;child_process&#39;),<br>      os       = require(&#39;os&#39;);</pre><pre>var server = null;</pre><pre>// Tasks incoming</pre><h3>Application compile</h3><pre>// Compile application<br>gulp.task(&#39;server:build&#39;, function() {</pre><pre> var build = child.spawnSync(&#39;go&#39;, [&#39;install&#39;]);<br> return build;</pre><pre>});</pre><p>Except that it’s not over because compilation errors are not including.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*xXChEnNR2NOT5eoOsuAQRg.gif" /></figure><pre>// Compile application<br>gulp.task(&#39;server:build&#39;, function() {</pre><pre> // Build application in the &quot;gobin&quot; folder<br> var build = child.spawnSync(&#39;go&#39;, [&#39;install&#39;]);</pre><pre> // Something wrong<br> if (build.stderr.length) {<br>  util.log(util.colors.red(&#39;Something wrong with this version :&#39;));<br>  var lines = build.stderr.toString()<br>   .split(&#39;\n&#39;).filter(function(line) {<br>   return line.length<br> });<br> for (var l in lines)<br>  util.log(util.colors.red(<br>   &#39;Error (go install): &#39; + lines[l]<br>  ));<br>  notifier.notify({<br>   title: &#39;Error (go install)&#39;,<br>   message: lines<br> });<br>}</pre><pre>return build;</pre><pre>});</pre><p>Errors are now displaying in the terminal and in a notify window.</p><h3>Launch server</h3><pre>// Launch server<br>gulp.task(&#39;server:spawn&#39;, function() {</pre><pre> // Stop the server<br> if (server &amp;&amp; server !== &#39;null&#39;) {<br>  server.kill();<br> }</pre><pre> // Application name<br> if (os.platform() == &#39;win32&#39;) {<br>  // Windows<br>  var path_folder = __dirname.split(&#39;\\&#39;);<br> } else {<br>  // Linux / MacOS<br>  var path_folder = __dirname.split(&#39;/&#39;);<br> }<br> var length = path_folder.length;<br> var app    = path_folder[length - parseInt(1)];</pre><pre> // Run the server<br> if (os.platform() == &#39;win32&#39;) {<br>  server = child.spawn(app + &#39;.exe&#39;);<br> } else {<br>  server = child.spawn(app);<br> }</pre><pre> // Display terminal informations<br> server.stderr.on(&#39;data&#39;, function(data) {<br>  process.stdout.write(data.toString());<br> });</pre><pre>});</pre><h3>Watching files</h3><pre>// Watch files<br>gulp.task(&#39;server:watch&#39;, function() {</pre><pre> gulp.watch([<br> &#39;*.go&#39;,<br> &#39;**/*.go&#39;,<br> ], sync([<br> &#39;server:build&#39;,<br> &#39;server:spawn&#39;<br> ], &#39;server&#39;));</pre><pre>});</pre><p>This task watching go files presents in the current folder and subfolders of your application.</p><h3>Let’s play…</h3><p>At the end of your Gulpfile, at this line for executing our 3 tasks.</p><pre>gulp.task(&#39;default&#39;, [&#39;server:build&#39;, &#39;server:spawn&#39;, &#39;server:watch&#39;]);</pre><p>Then run with the default gulp command.</p><pre>gulp</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*lJfBcU6DH0hCU_owRkFdrg.gif" /></figure><p>Complete code available in this <a href="https://gist.github.com/EtienneR/a7d9e956ace886516299">Gist</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee5e231d133d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Codeigniter layout]]></title>
            <link>https://medium.com/@etiennerouzeaud/codeigniter-layout-b97b249b25c5?source=rss-fd941f66a978------2</link>
            <guid isPermaLink="false">https://medium.com/p/b97b249b25c5</guid>
            <category><![CDATA[codeigniter]]></category>
            <category><![CDATA[temple]]></category>
            <category><![CDATA[layout]]></category>
            <dc:creator><![CDATA[Etienne Rouzeaud]]></dc:creator>
            <pubDate>Mon, 07 Dec 2015 14:13:52 GMT</pubDate>
            <atom:updated>2015-12-07T14:13:52.152Z</atom:updated>
            <content:encoded><![CDATA[<p>When you coding a website, you need to do layout templating. In Codeigniter 2 or 3, there is not official library for this job.</p><h4>The custom library</h4><p>In the “application/libraries” create a new library “Template.php” :</p><pre>&lt;?php if ( ! defined(&#39;BASEPATH&#39;)) exit(‘No direct script access allowed’);</pre><pre>class Template {</pre><pre> var $template_data = array();</pre><pre> function set($name, $value)<br> {<br>  $this-&gt;template_data[$name] = $value;<br> }</pre><pre> function load($template = &#39;&#39;, $view = &#39;&#39;, $view_data = array(), $return = FALSE)<br> {<br>  $this-&gt;CI = &amp;get_instance();<br>  $this-&gt;set(&#39;contents&#39;, $this-&gt;CI-&gt;load-&gt;view($view, $view_data, TRUE));   <br>  return $this-&gt;CI-&gt;load-&gt;view($template, $this-&gt;template_data, $return);<br> }</pre><pre>}</pre><pre>/* End of file Template.php */<br>/* Location: ./system/application/libraries/Template.php */</pre><p>With the “load()” function you will can load the template ($template), the view ($view) and datas ($view_data).</p><h4>Views</h4><p>In the views folder (“application/views”), create 2 files :</p><ul><li>“view_layout.php”</li><li>“view_foo.php”</li></ul><blockquote>The layout</blockquote><p>In the “view_layout.php” :</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br> &lt;meta charset=&quot;utf-8&quot; /&gt;<br> &lt;title&gt;&lt;?= $title_page ?&gt;&lt;/title&gt;<br> &lt;link rel=&quot;stylesheet&quot; href=<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">&quot;https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css</a>&quot;&gt;<br>&lt;/head&gt;<br>&lt;body class=&quot;container-fluid&quot;&gt;</pre><pre> &lt;?= $contents ?&gt;</pre><pre> &lt;footer&gt;Your copyright&lt;/footer&gt;</pre><pre>&lt;/body&gt;<br>&lt;/html&gt;</pre><blockquote>The content page</blockquote><p>In the “view_foo.php” :</p><pre>&lt;h1&gt;&lt;?= $title ?&gt;&lt;/h1&gt;<br>&lt;p&gt;<br> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod<br> tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,<br> quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo<br> consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse<br> cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non<br> proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br>&lt;/p&gt;</pre><h4>The controller</h4><p>In the constructor or in the function of your controller, you must load the Template library :</p><pre>$this-&gt;load-&gt;library(&#39;Template&#39;);</pre><p>Off course, you can add this library in the autoload in the “application/config/autoload.php”.</p><p>Then, in the dedicated function, use $this-&gt;template-&gt;load() instead the classic $this-&gt;load-&gt;view():</p><pre>$data[&#39;title&#39;] = &#39;My foo page&#39;;<br>$this-&gt;template-&gt;load(&#39;view_layout&#39;, &#39;view_foo&#39;, $data);</pre><p>More about this template library : <a href="http://jeromejaglale.com/doc/php/codeigniter_template">http://jeromejaglale.com/doc/php/codeigniter_template</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b97b249b25c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Codeigniter 3 : “url_title()” function & accents]]></title>
            <link>https://medium.com/@etiennerouzeaud/codeigniter-3-url-title-function-accents-4405b61d1ec0?source=rss-fd941f66a978------2</link>
            <guid isPermaLink="false">https://medium.com/p/4405b61d1ec0</guid>
            <category><![CDATA[accents]]></category>
            <category><![CDATA[codeigniter]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Etienne Rouzeaud]]></dc:creator>
            <pubDate>Wed, 18 Nov 2015 17:06:07 GMT</pubDate>
            <atom:updated>2015-11-18T17:06:27.375Z</atom:updated>
            <content:encoded><![CDATA[<h4>The problem</h4><p>With not accents :</p><pre>$this-&gt;load-&gt;helper(&quot;url&quot;);</pre><pre>$title     = &quot;Mint tea&quot;;<br>$url_title = url_title($title, &quot;dash&quot;, TRUE);</pre><pre>echo url_title; // mint-tea</pre><p>It’s working good but if you try with french accents :</p><pre>$this-&gt;load-&gt;library(&quot;url&quot;);</pre><pre>$title     = &quot;Thé à la menthe&quot;;<br>$url_title = url_title($title, &quot;dash&quot;, TRUE);</pre><pre>echo url_title; // thé-à-la-menthe</pre><p>The “url_title” function returns “thé-à-la-menthe” instead “the-a-la-menthe” :(</p><h4>The fix</h4><p>Don’t worry, Codeigniter is a good framework. Indeed, in the “Text Helper”, there is a function who can fix this problem, “convert_accented_characters” :</p><pre>$this-&gt;load-&gt;helper(array(&quot;url&quot;, &quot;text&quot;));</pre><pre>$title     = &quot;Thé à la menthe&quot;;<br>$url_title = convert_accented_characters(url_title($title, &quot;dash&quot;, TRUE));</pre><pre>echo $url_title; // the-a-la-menthe</pre><p>Of course, you can edit the “url_title” function simply at the source. For that, open the file “system\helpers\url_helper.php”, find the “url_title” function (“CTRL + R” in Sublime Text) and replace the return code with the “convert_accented_characters” function :</p><pre>return trim(trim(convert_accented_characters($str), $separator));</pre><h4>Sources</h4><ul><li>“url_title” function: <a href="http://www.codeigniter.com/user_guide/helpers/url_helper.html?highlight=url_title#url_title">http://www.codeigniter.com/user_guide/helpers/url_helper.html?highlight=url_title#url_title</a></li><li>“convert_accented_characters” function : <a href="http://www.codeigniter.com/user_guide/helpers/text_helper.html?highlight=convert#convert_accented_characters">http://www.codeigniter.com/user_guide/helpers/text_helper.html?highlight=convert#convert_accented_characters</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4405b61d1ec0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Change default delimiters templating with “template.Delims”]]></title>
            <link>https://medium.com/@etiennerouzeaud/change-default-delimiters-templating-with-template-delims-857938a0b661?source=rss-fd941f66a978------2</link>
            <guid isPermaLink="false">https://medium.com/p/857938a0b661</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[angularjs]]></category>
            <dc:creator><![CDATA[Etienne Rouzeaud]]></dc:creator>
            <pubDate>Mon, 14 Sep 2015 22:41:42 GMT</pubDate>
            <atom:updated>2015-09-14T22:41:42.463Z</atom:updated>
            <content:encoded><![CDATA[<p>If you work with Golang and AngularJS (or another Javascript Framework), by default, you will get a problem with delimiters templating because both are using double opening &amp; closing braces “{{ }}”. We can change Golang delimiters templating to double opening &amp; closing brackets “[[ ]]” (or anything else). For that, we gonna use the “<a href="http://golang.org/pkg/html/template/#Template.Delims">template.Delims</a>” function of “<a href="http://golang.org/pkg/html/template/">html/template</a>”.</p><h3>A simple page</h3><pre>package main</pre><pre>import (<br> &quot;html/template&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br>)</pre><pre>type Infos struct {<br> Title, Content string<br>}</pre><pre>func main() {<br> port := &quot;:3000&quot;<br> log.Println(&quot;Starting Web Server 127.0.0.1&quot; + port)<br> <br> http.HandleFunc(&quot;/&quot;, indexHandler) <br> <br> err := http.ListenAndServe(port, nil)<br> if err != nil {<br>  log.Fatal(&quot;ListenAndServe: &quot;, err)<br> }<br>}</pre><pre>func indexHandler(w http.ResponseWriter, r *http.Request) {<br> data := Infos{&quot;Your title page&quot;, &quot;A classic lorem ipsum content&quot;}</pre><pre> pageFile := &quot;index.html&quot;</pre><pre> tmpl, err := template.New(pageFile).Delims(&quot;[[&quot;, &quot;]]&quot;).ParseFiles(pageFile)</pre><pre> if err != nil {<br>  http.Error(w, err.Error(), http.StatusInternalServerError)<br> }</pre><pre> tmpl.Execute(w, data)<br>}</pre><p>The most important is to put the value of file page name in the “template.New” function. If you don’t do that, you will get a panic error…</p><p>In the “index.html” file, we call values in “[[ ]]” delimiters instead “{{ }}”:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br> &lt;title&gt;[[ .Title ]]&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;</pre><pre>&lt;p&gt;[[ .Content ]]&lt;/p&gt;</pre><pre>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>A layout</h3><p>In a layout, leave empty the “template.New()” string parameter.</p><pre>package main</pre><pre>import (<br> &quot;html/template&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br>)</pre><pre>type Infos struct {<br> Title, Content string<br>}</pre><pre>func main() {<br> port := &quot;:3000&quot;<br> log.Println(&quot;Starting Web Server 127.0.0.1&quot; + port)<br> <br> http.HandleFunc(&quot;/&quot;, indexHandler)<br> <br> if err != nil {<br>  log.Fatal(&quot;ListenAndServe: &quot;, err)<br> }<br>}</pre><pre>func indexHandler(w http.ResponseWriter, r *http.Request) {<br> data := Infos{&quot;Your title page&quot;, &quot;A classic lorem ipsum content&quot;}<br> <br> tmpl, err := template.New(&quot;&quot;).Delims(&quot;[[&quot;, &quot;]]&quot;).ParseFiles(&quot;layout.html&quot;, &quot;index.html&quot;)</pre><pre> if err != nil {<br>  http.Error(w, err.Error(), http.StatusInternalServerError)<br> } </pre><pre> tmpl.ExecuteTemplate(w, &quot;layout&quot;, data)<br>}</pre><p>In the “layout.html” file:</p><pre>[[ define &quot;layout&quot; ]]</pre><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br> &lt;title&gt;[[ .Title ]]&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;</pre><pre>[[ template &quot;content&quot; . ]]</pre><pre>&lt;/body&gt;<br>&lt;/html&gt;</pre><pre>[[ end ]]</pre><p>And in the “index.html”:</p><pre>[[ define &quot;content&quot; ]]<br>&lt;p&gt;[[ .Content ]]&lt;/p&gt;<br>[[ end ]]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=857938a0b661" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A RSS feed valid in Go]]></title>
            <link>https://medium.com/@etiennerouzeaud/a-rss-feed-valid-in-go-edfc22e410c7?source=rss-fd941f66a978------2</link>
            <guid isPermaLink="false">https://medium.com/p/edfc22e410c7</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Etienne Rouzeaud]]></dc:creator>
            <pubDate>Mon, 17 Aug 2015 12:25:49 GMT</pubDate>
            <atom:updated>2015-08-17T12:25:49.592Z</atom:updated>
            <content:encoded><![CDATA[<p>For parsing a RSS feed, we gonna use the native library “encoding/xml” and define the good data structure of our futur XML file.</p><h3>The base foundation</h3><p>We begin with the node global “rss” and “channel” and the “xml.NewEncoder” function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47ddbd7e870cf7e60de00bbbeb433a99/href">https://medium.com/media/47ddbd7e870cf7e60de00bbbeb433a99/href</a></iframe><p>Then we add the node “item”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37316ade69fdfe97b876a3705c1d8d0f/href">https://medium.com/media/37316ade69fdfe97b876a3705c1d8d0f/href</a></iframe><p>Ok, but we need an array structure for “item”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d41737cf1b9a537467d63f5a8400371/href">https://medium.com/media/6d41737cf1b9a537467d63f5a8400371/href</a></iframe><h3>In a webserver</h3><p>Let’s do this with a webserver and the “xml.MarshalIndent” function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c43bd8edd5b34271438eb60750307bf/href">https://medium.com/media/9c43bd8edd5b34271438eb60750307bf/href</a></iframe><h3>The good date format in “pubDate”</h3><p>We need to use the “time” library with a valid format date RSS.</p><p>Let’s check with the official documentation: <a href="https://validator.w3.org/feed/docs/error/InvalidRFC2822Date.html">https://validator.w3.org/feed/docs/error/InvalidRFC2822Date.html</a></p><p>Then we can choose in Go a similar format date: <a href="http://golang.org/pkg/time/#pkg-constants">http://golang.org/pkg/time/#pkg-constants</a></p><p>There is a matching with RFC1123Z:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1b733aedb76b9d45161998ce230862d/href">https://medium.com/media/e1b733aedb76b9d45161998ce230862d/href</a></iframe><h3>Bonus: Markdown to HTML</h3><p>If you have markdown syntax in your description, you will need to encode this syntax to HTML code. We gonna use Blackfriday library coded by Russ Ross:</p><pre>go get github.com/russross/blackfriday</pre><p>Then, we import this library in the code and we encode “Description” value to HTML format in a loop (“for range”):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbe1d013e3d5b0ccf6c80b976d769666/href">https://medium.com/media/dbe1d013e3d5b0ccf6c80b976d769666/href</a></iframe><h3>Sources</h3><ul><li><a href="http://golang.org/pkg/encoding/xml/#example_Encoder">http://golang.org/pkg/encoding/xml/#example_Encoder</a></li><li><a href="http://www.alexedwards.net/blog/golang-response-snippets#xml">http://www.alexedwards.net/blog/golang-response-snippets#xml</a></li><li><a href="http://validator.w3.org/feed/#validate_by_input">http://validator.w3.org/feed/#validate_by_input</a></li><li><a href="https://validator.w3.org/feed/docs/error/InvalidRFC2822Date.html">https://validator.w3.org/feed/docs/error/InvalidRFC2822Date.html</a></li><li><a href="http://github.com/russross/blackfriday">http://github.com/russross/blackfriday</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edfc22e410c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>