<?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 Odohi David on Medium]]></title>
        <description><![CDATA[Stories by Odohi David on Medium]]></description>
        <link>https://medium.com/@odohi.david?source=rss-27519e23f515------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*hw7rcuoWVGNxl6qDXEGQig.jpeg</url>
            <title>Stories by Odohi David on Medium</title>
            <link>https://medium.com/@odohi.david?source=rss-27519e23f515------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:37:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@odohi.david/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[Interesting Javascript Features.]]></title>
            <link>https://medium.com/@odohi.david/interesting-javascript-features-fa4ee1a95d03?source=rss-27519e23f515------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa4ee1a95d03</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[js]]></category>
            <dc:creator><![CDATA[Odohi David]]></dc:creator>
            <pubDate>Sun, 05 Jul 2020 23:41:52 GMT</pubDate>
            <atom:updated>2020-07-05T23:41:52.731Z</atom:updated>
            <content:encoded><![CDATA[<p>Some few useful javascript features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*HaCuZ3o2Hmt8DP8oobILoA.png" /><figcaption>image from thepracticaldev</figcaption></figure><p>Over the years, javascript has evolved and various features has been added to the language syntax. Some of the syntax seems strange and unknown, so here are some of the ones I have discovered in the few years i have been working with javascript.</p><p><strong>Property Accessors</strong></p><p>The regular way of accessing object properties in javascript is similar to other C like languages e.g getting the firstname property of a Person object is <em>Person.firstname</em>.<br>Another way of accessing these properties is by treating the properties like keys of a map e.g <em>Person[‘firstname’]</em>. This way of accessing object properties is not limited to only fields/attributes but methods as well can be accessed this way. Below is an example using accessing methods like key of a map.</p><pre>// create an array arr<br>var arr = [“hello”];</pre><pre>// access the push method of array prototype.<br>arr[“push”](“Spankie”);</pre><pre>console[“log”](arr); // prints out: [“hello”, “Spankie”]</pre><p><strong>Javascript object spreading</strong></p><p>Concatenating objects properties in javascript has always been done with the `<em>Object</em>` prototype method `<em>assign</em>`, but there are other ways this can be achieved, which is done using the spread syntax `<em>…</em>`. here is an example;</p><pre>let obj1 = { name: “Spankie” };<br>let obj2 = {<br>  greeting: “Hello”,<br>  greet: () =&gt; console.log(this.greeting),<br>  sayhello: function() {<br>    console.log(this.greeting);<br>  }<br>};</pre><pre>// concatenating obj2 properties into obj1…<br>let obj3 = {…obj1, …obj2}<br>obj3.greet(); // prints out: undefined<br>obj3.sayhello(); // prints out: “Hello”</pre><p><strong>Javascript Object deconstructions</strong></p><p>As mentioned earlier, getting object attributes can be done in several ways, and another way of doing that is by object deconstruction. This is a way fetching a particular attribute from an object and assigning it to a variable with the same name as the attribute. For example, retrieving a `<em>first_name</em>` attribute from a `<em>person</em>` object and assigning it to a variable name `<em>first_name</em>` can be done easily like this;</p><pre>const person = {first_name: “Spankie”, last_name: “Dee”};<br>const { first_name } = person;<br>console.log(first_name); // prints out “Spankie”;</pre><p><strong>Renaming deconstructed variables</strong></p><pre><br>const person = {<br>  first_name: “Spankie”,<br>  last_name: “Dee”,<br>  address: {<br>    street: “1 Main st.”,<br>    city: “Lagos”,<br>    country: “Nigeria”<br>  }<br>};<br>const { address: myaddress } = person;<br>console.log(myaddress); // prints out “{street: “1 Main st.”, city: “Lagos”, country: “Nigeria”}”</pre><p><strong>Deconstructing nested object attributes</strong></p><pre>const person = {<br>  first_name: “Spankie”,<br>  last_name: “Dee”,<br>  address: {<br>    street: “1 Main st.”,<br>    city: “Lagos”,<br>    country: “Nigeria”<br>  }<br>};<br>const { address: { city, country } } = person;<br>console.log(city, country); // prints out “Lagos Nigeria”;<br>console.log(address); // Error: address is not defined.</pre><p><strong>Parsing Objects and string to json</strong></p><p>Using `<em>json.parse()</em>` with template literals can be quite tricky…</p><pre>const a = “A girl has no face”;<br>const b = {stark: “Winter is coming.”};<br>console.log(JSON.parse(a)); // this would throw an unexpected token error<br>console.log(JSON.parse(b)); // this would throw an unexpected token error<br>console.log(JSON.parse(`${a}`)); // this would throw an unexpected token error<br>console.log(JSON.parse(`”${a}”`)); // this would log “A girl has no face”<br>console.log(JSON.parse(`”${b}”`)); // this would log “[object Object]”<br>console.log(JSON.parse(`${b}`)); // this would throw an unexpected token error</pre><p>What will work in any of these cases is:</p><pre>console.log(JSON.parse(JSON.stringify(a)));</pre><pre>// or</pre><pre>console.log(JSON.parse(JSON.stringify(b)));</pre><p>Both will run fine.</p><p><strong>Setters and getters object accessors in javascript.</strong></p><p>Accessing object OOP style using getters and setters method are quite popular, javascript is not exempted from this as well, in fact it is quite interesting how it is done in javascript.</p><p>Setters and getters can be defined for an attribute using the `<em>get</em>` and `<em>set</em>` keywords in an object. Here is an example showing how it is done;</p><pre>const vehicle = {<br> name: “Volvo”,<br> year: “1999”,<br> // using getters and setter to set/get the year.<br> get description() {<br>   return `This ${this.name} was made in ${this.year}`;<br> },<br> set description(desc) {<br>   var descs = desc.toString().split(‘ ‘);<br>   this.name = descs[0];<br>   this.year = descs[1];<br> }<br>}</pre><pre>vehicle.description = “Mercedes 2018”;<br>console.log(vehicle.description); // prints out “Mercedes was made in 2018”</pre><p><strong>Assigning variable object attributes</strong></p><p>Sometimes you may want to assign a value to an object attribute without knowing exactly the name of the attribute, but the name is the value of another variable. Here is an example explaining this;</p><pre>const carname = “volkswagen”;<br>const caryear = 1937;</pre><pre>let CarsFounded = {<br> “bmw”: 1916,<br> “mercedes benz”: 1926,<br> [carname]: caryear,<br>}</pre><pre>console.log(CarsFounded); // prints out: { bmw: 1916, ‘mercedes benz’: 1926, volkswagen: 1937 }<br>console.log(CarsFounded[carname]); // prints out: 1937</pre><p>Thanks for reading this to the end :). If you enjoyed or learned something new, please clap for the article (<em>remember you can clap up to 50 times</em>), and share, so that others can see it too.</p><p>Originally published <a href="https://dev.to/spankie/interesting-javascript-features-74j">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa4ee1a95d03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with influxDB (with Golang example)]]></title>
            <link>https://medium.com/spankie/getting-started-with-influxdb-with-golang-example-10990c5efee7?source=rss-27519e23f515------2</link>
            <guid isPermaLink="false">https://medium.com/p/10990c5efee7</guid>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[influxdata]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[influxdb]]></category>
            <dc:creator><![CDATA[Odohi David]]></dc:creator>
            <pubDate>Fri, 15 Feb 2019 09:08:14 GMT</pubDate>
            <atom:updated>2019-02-15T09:08:14.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*d3gFsCJU_IE84zMn5894xw.png" /></figure><p>InfluxDB is one of the popular time series database out there. In this article, I’ll try to explain some of the key concepts needed to get you up-and-running with InfluxDB. This article assumes that you have InfluxDB already installed on your machine. if you don&#39;t, you can install it by following <a href="https://influxdbcom.readthedocs.io/en/latest/content/site/download/">this instructions</a>.</p><p><strong>Primer</strong><br>A time series database should not be confused with relational databases as they are totally different. A time series is basically a series of points indexed in time order. Examples of Time Series Data include:</p><ul><li>Measuring the level of unemployment each month of the year</li><li>Tracking the product that sold more at a particular time in an e-commerce site.</li><li>Tracking the most visited product in an e-commerce website</li><li>Price of stocks and shares taken at a regular interval.</li></ul><p>Essentially, the root of everything is time in InfluxDB, as all columns have a special time column.</p><p><strong>Key Concepts</strong><br>InfluxDB doesn’t impose any schema structure on the data you are going to store. Developers that are already familiar with SQL can quickly pick up InfluxDB as it provides an SQL-like syntax. This has particularly led to an increase adoption of influxdb. <br><br><strong>Database: </strong>InfluxDB has a notion of database<br><br><strong>Measurement: </strong>Is a description of the data that are stored. It is similar to a table in SQL.<br><br><strong>Fields: </strong>Comprised of fieldKeys and fieldValues. Fields are required and are not indexed. This means that Queries using Fields to filter data are relatively slow.<br><br><strong>Tags:</strong> Comprised of tagKeys and tagValues. Tags are optional and can be indexed. This means that Queries using Tags are much faster than their Fields counterpart.<br><br>In this article We will be building a simple shop to display our cool products and take a measurement of how much visits each product get. we need to install the following;</p><ul><li><strong><em>InfluxDB Go Client Library</em></strong></li></ul><p>InfluxDB is written completely with Go with no external dependencies and it makes sense that the team provides a <a href="https://github.com/influxdata/influxdb">Go client</a> to make interfacing with InfluxDB easy from a Go application.</p><ul><li><strong><em>Graphana</em></strong></li></ul><p>Graphana is an open-source, general purpose dashboard and graph composer, which runs as a web application. It is a Data visualization &amp; Monitoring platform and it supports graphite, InfluxDB or opentsdb as backends<br><br>N/B: This article assumes you already have <strong>Golang</strong> installed on your OS, if you don&#39;t you can follow the instructions <a href="https://golang.org/dl/">here</a></p><ul><li><a href="https://github.com/go-chi/chi"><strong><em>go-chi chi router</em></strong></a><strong><em>:</em></strong> This is a lightweight, idiomatic and composable router for building Go HTTP services.</li><li><a href="http://github.com/influxdata/influxdb/client/v2"><strong><em>InfluxDB Go Client</em></strong></a></li><li><a href="http://tachyons.io/"><strong><em>UI Library tachyons.io</em></strong></a> is a library for creating fast loading, highly readable, and 100% responsive interfaces with as little css as possible.</li></ul><p>Now we have our dependencies set let&#39;s write some code. Thankfully, getting a web application up and running in golang is very simple! All we need is a server and some html to serve right?</p><p>Our final website folder structure will look like this:</p><pre>.<br>+-- modules<br>|   +-- shops<br>|       +-- db.go<br>|       +-- handler.go<br>|       +-- model.go<br>+-- public<br>|   +-- assets<br>|       +-- css<br>|           +-- tachyons.min.css<br>|       +-- img<br>|           +-- camera.jpeg<br>|           +-- glass.jpeg<br>|           +-- toy.jpeg<br>|           +-- watch.jpeg<br>|   +-- index.html<br>|   +-- products.html<br>|   +-- 404.html<br>+-- main.go<br>+-- README.md<br>+-- .gitignore</pre><p>Lets create a folder called <strong><em>GO__INFLUX_APP </em></strong>First we create a public folder and add <a href="https://github.com/spankie/go-influx/tree/develop/public"><em>this files</em></a><em> to it.</em></p><p>Next Create a Database. In your terminal type:</p><pre>step1: influx // to enter influx DB mode<br>step2: create database go_influx // to create the db</pre><p>Inside the folder create a file called main.go in the root directory and add the following lines of code to it.</p><pre>package main<br><br>import (<br>	&quot;net/http&quot;<br>	&quot;github.com/go-chi/chi&quot; // http router<br>	&quot;github.com/go-chi/chi/middleware&quot; // package for commonly used middlewares<br>	log &quot;github.com/sirupsen/logrus&quot; // cool logger package<br>	&quot;github.com/spankie/go-influx/handlers&quot; // handler packages<br>)<br><br>func main() {<br>	r := chi.NewRouter()<br>	r.Use(middleware.Logger)<br>	r.Use(middleware.Recoverer)<br><br>	fileServer := http.StripPrefix(&quot;/assets/&quot;, http.FileServer(http.Dir(&quot;./public/assets&quot;)))<br>	r.Get(&quot;/assets/*&quot;, func(w http.ResponseWriter, r *http.Request) {<br>		w.Header().Set(&quot;Vary&quot;, &quot;Accept-Encoding&quot;)<br>		w.Header().Set(&quot;Cache-Control&quot;, &quot;public, max-age=7776000&quot;)<br>		fileServer.ServeHTTP(w, r)<br>	})<br><br>	// Define App routes<br>	<br>	//Homepage<br>	r.Get(&quot;/&quot;, shops.GetAllProducts)<br>	<br>	// Product page handler<br>	r.Get(&quot;/product/{ID}&quot;, shops.GetProduct)<br><br>	r.NotFound(func(w http.ResponseWriter, r *http.Request) {<br>		http.ServeFile(w, r, &quot;./public/404.html&quot;)<br>	})<br><br>	log.Print(&quot;👉  Server started at 127.0.0.1:3333&quot;)<br>	http.ListenAndServe(&quot;:3333&quot;, r)<br>}</pre><p>Here we have defined three routes to display the home page with the listing of all the products (/), the product details page (/product/{id}), where ID is the id of the product we want to view. The last route is any route not explicitly defined which will render a 404 page to the user.</p><p>N/B: We will use an array of static products for this article.</p><p>Create a folder called <strong><em>modules/shops </em></strong>and add a file called <strong><em>model.go </em></strong>(which contains the array of products we will use and other methods):</p><pre>package shops<br><br>import (<br>	&quot;errors&quot;<br>	&quot;log&quot;<br>	&quot;time&quot;<br>)<br><br>// Product structure of my cool shop product<br>type Product struct {<br>	ID          int     `json:&quot;id&quot;`<br>	Name        string  `json:&quot;name&quot;`<br>	Price       float32 `json:&quot;price&quot;`<br>	Image       string  `json:&quot;image&quot;`<br>	Description string  `json:&quot;description&quot;`<br>	Views       string<br>}<br><br>// ProductMeasurement schema of product measurement<br>type ProductMeasurement struct {<br>	ProductID   int `json:&quot;id&quot;`<br>	ProductName string<br>	time        time.Time<br>}<br><br>var allProducts = []Product{<br>	Product{ID: 0, Name: &quot;Watch&quot;, Price: 56.2, Image: &quot;/assets/img/watch.jpeg&quot;, Description: &quot;Nice Watch&quot;},<br>	Product{ID: 1, Name: &quot;Camera&quot;, Price: 34.2, Image: &quot;/assets/img/camera.jpeg&quot;, Description: &quot;Nice Camera&quot;},<br>	Product{ID: 2, Name: &quot;Glass&quot;, Price: 24.2, Image: &quot;/assets/img/glass.jpeg&quot;, Description: &quot;Nice Glass&quot;},<br>	Product{ID: 3, Name: &quot;Toy&quot;, Price: 56.2, Image: &quot;/assets/img/toy.jpeg&quot;, Description: &quot;Nice Toy&quot;},<br>}<br><br>// GetAll fetches all products in my shop<br>func (product Product) GetAll() []Product {<br>	return allProducts<br>}<br><br>// Get fetches a particular product in my shop identified By its ID<br>func (product Product) Get(id int) (Product, error) {<br>	if id &lt; 0 &amp;&amp; len(allProducts) &gt;= id {<br>		log.Println(id)<br>		return Product{}, errors.New(&quot;No product found&quot;)<br>	}<br>	return allProducts[id], nil<br>}</pre><p>We need to create a file called <strong><em>DB.go</em></strong> because =&gt; (This is to abstract all Database access from the other parts of the app)<br><br>The `Insert` function takes a `productMeasurement` type and saves it in the Database. While the queryDB function is a convenience function that receives string query, executes the query and return the result.</p><pre>package shops<br><br>import (<br>	&quot;log&quot;<br>	&quot;time&quot;<br><br>	&quot;github.com/influxdata/influxdb/client/v2&quot;<br>)<br><br>const (<br>	// MyDB specifies name of database<br>	MyDB = &quot;go_influx&quot;<br>)<br><br>// Insert saves points to database<br>func Insert(productMeasurement map[string]interface{}) {<br>	c, err := client.NewHTTPClient(client.HTTPConfig{<br>		Addr: &quot;http://localhost:8086&quot;,<br>	})<br>	if err != nil {<br>		log.Fatal(err)<br>	}<br>	defer c.Close()<br><br>	// Create a new point batch<br>	bp, err := client.NewBatchPoints(client.BatchPointsConfig{<br>		Database:  MyDB,<br>		Precision: &quot;s&quot;,<br>	})<br>	if err != nil {<br>		log.Fatal(err)<br>	}<br><br>	// Create a point and add to batch<br>	tags := map[string]string{&quot;productView&quot;: productMeasurement[&quot;ProductName&quot;].(string)}<br>	fields := productMeasurement<br><br>	pt, err := client.NewPoint(&quot;products&quot;, tags, fields, time.Now())<br>	if err != nil {<br>		log.Fatal(err)<br>	}<br>	bp.AddPoint(pt)<br><br>	// Write the batch<br>	if err := c.Write(bp); err != nil {<br>		log.Fatal(err)<br>	}<br><br>	// Close client resources<br>	if err := c.Close(); err != nil {<br>		log.Fatal(err)<br>	}<br>}<br><br>// queryDB convenience function to query the database<br>func queryDB(cmd string) (res []client.Result, err error) {<br>	q := client.Query{<br>		Command:  cmd,<br>		Database: MyDB,<br>	}<br>	c, err := client.NewHTTPClient(client.HTTPConfig{<br>		Addr: &quot;http://localhost:8086&quot;,<br>	})<br>	if response, err := c.Query(q); err == nil {<br>		if response.Error() != nil {<br>			return res, response.Error()<br>		}<br>		res = response.Results<br>	} else {<br>		return res, err<br>	}<br>	return res, nil<br>}</pre><p>Now lets analyze each function:<br><br>The `Insert()` function creates a client to connect to the database at `localhost` port `8086` which is the default port for the influxDB server<br><br>Next a point batch is created to store points to be saved to the DB. A point is then created to store the ProductMeasurement details which includes the time of visit, the id of the product as well as the Name of the product being viewed.<br><br>Here is how the DB looks like after insert:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/0*UAsYW8wFiLb_YBn9.png" /><figcaption>How the influx database looks like…</figcaption></figure><p>The time field is indexed and stores the exact time the product was viewed. This time can be used to query the DB for analysis.<br><br>The `queryDB()` function queries the influxDB and return the result as an array of client.Result type.<br><br>Finally lets create a file called `handler.go` and add the following lines of code to it.<br><br><strong>INSERT REASON FOR HANDLER.GO</strong><br>Each handler function will perform a specific task required for rendering a page to the route being accessed. e.g GetAllProducts() gets all products and renders it in the index.html template.</p><pre>package shops<br><br>import (<br>	&quot;encoding/json&quot;<br>	&quot;fmt&quot;<br>	&quot;html/template&quot;<br>	&quot;log&quot;<br>	&quot;net/http&quot;<br>	&quot;os&quot;<br>	&quot;path&quot;<br>	&quot;strconv&quot;<br>	&quot;time&quot;<br><br>	&quot;github.com/fatih/structs&quot;<br>	&quot;github.com/go-chi/chi&quot;<br>)<br><br>// GetAllProducts fetches all products in my shop<br>func GetAllProducts(w http.ResponseWriter, r *http.Request) {<br>	t := template.New(&quot;index.html&quot;) // Create a template.<br>	cwd, _ := os.Getwd()<br>	p := path.Join(cwd, &quot;public&quot;, &quot;index.html&quot;)<br>	t, err := t.ParseFiles(p) // Parse template file.<br>	if err != nil {<br>		log.Println(err)<br>	}<br>	products := Product{}.GetAll() // Get current user infomration.<br>	err = t.Execute(w, products)   // merge.<br>	if err != nil {<br>		log.Println(err)<br>	}<br>}<br><br>// GetProduct handler for fetching a particular product<br>func GetProduct(w http.ResponseWriter, r *http.Request) {<br>	ID, err := strconv.Atoi(chi.URLParam(r, &quot;ID&quot;))<br>	if err != nil {<br>		log.Println(err)<br>		return<br>	}<br>	product, err := Product{}.Get(ID)<br>	if err != nil {<br>		log.Println(err)<br>	}<br>	t := template.New(&quot;product.html&quot;) // Create a template.<br>	cwd, _ := os.Getwd()<br>	p := path.Join(cwd, &quot;public&quot;, &quot;product.html&quot;)<br>	t, err = t.ParseFiles(p) // Parse template file.<br>	if err != nil {<br>		log.Println(err)<br>	}<br>	res, err := queryDB(fmt.Sprintf(&quot;select count(ProductID) from products where ProductID = %d&quot;, product.ID))<br>	if err != nil {<br>		log.Println(err)<br>	}<br>	result := res[0]<br>	if len(result.Series) &gt; 0 {<br>		product.Views = string(result.Series[0].Values[0][1].(json.Number))<br>	} else {<br>		product.Views = &quot;0&quot;<br>	}<br>	err = t.Execute(w, product) // merge.<br>	if err != nil {<br>		log.Println(err)<br>	}<br><br>	pm := &amp;ProductMeasurement{product.ID, product.Name, time.Now()}<br><br>	Insert(structs.Map(pm))<br>}</pre><p>Now lets see what we have so far; To Start your app, in your terminal type:</p><pre>go run main.go</pre><p><strong>Included here is the screenshot of what it looks like when you start the browser.</strong></p><p>Visit `localhost:3333` on your browser, and you should see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cy7kdY3ABnSidez-.png" /><figcaption>Images from pexels.com</figcaption></figure><p>Clicking on a product should take you to a page that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bf7oTkVouKODqLTO.png" /><figcaption>Images from pexels.com</figcaption></figure><p>We need a way to graphically view this data we just saved in our awesome influxDB</p><p>These views can be analyzed/viewed using an awesome tool called <a href="http://docs.grafana.org/"><em>grafana</em></a>.</p><p>After installing grafana from <a href="http://docs.grafana.org/">here</a>, set it up by following their straightforward guide on their website. Then do the following:</p><ul><li>Create a new dashboard with a graph panel.</li><li>Make a query as specified in this screenshot below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4gaf8kjv8hBQWdi-.png" /><figcaption>Grafana query</figcaption></figure><ul><li>The axes tab should look like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DjBx94UXztU9ojlz.png" /><figcaption>axes tab</figcaption></figure><ul><li>Display tab should also look like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sVQUdW_m4E-z7m6b.png" /><figcaption>Display tab</figcaption></figure><ul><li>Your graph should finally look like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fiGlYpWMDIaTVsAN.png" /><figcaption>Final graph</figcaption></figure><p><strong>Conclusion:</strong></p><p>In this article we looked at how to work with InfluxDB to monitor time series data, I hope you have learnt a lot, to start building awesome stuff. Hack ON!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10990c5efee7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spankie/getting-started-with-influxdb-with-golang-example-10990c5efee7">Getting started with influxDB (with Golang example)</a> was originally published in <a href="https://medium.com/spankie">Spankie’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upload images to AWS S3 bucket in a golang web application]]></title>
            <link>https://medium.com/spankie/upload-images-to-aws-s3-bucket-in-a-golang-web-application-2612bea70dd8?source=rss-27519e23f515------2</link>
            <guid isPermaLink="false">https://medium.com/p/2612bea70dd8</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Odohi David]]></dc:creator>
            <pubDate>Fri, 08 Feb 2019 11:36:52 GMT</pubDate>
            <atom:updated>2019-09-13T08:01:18.269Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Image result for golang aws s3 bucket" src="https://cdn-images-1.medium.com/proxy/1*Z4Bl8bsU59fTvddWZMx54A.jpeg" /></figure><p>I was trying to upload an image to aws (Amazon Web Service) for the first time and couldn’t find a comprehensive guide, I had to search for every bit of the process. Here are my findings I hope it helps you 😇.</p><p>The code example is not the ideal way to structure your application, config variables should be gotten from <em>environment variable. </em>The goal is to upload any file to an S3 bucket, not to structure a web application for production 🙂.</p><p>First of all you need an aws account. You can create on <a href="https://aws.amazon.com/free/"><strong>here</strong></a>. You get a free trial which is sufficient for you to learn how to upload images over there.</p><p>You might want to know why you would want to upload images on aws. Most likely you want to upload to a storage server so that your storage is managed independent of your application. Multiple services or application can access your stored files independent of each other. There are other alternatives like google cloud storage and digital ocean as well, but we are going to be focusing on aws here. If you need to know how to upload to those other platforms you could drop a comment and i’ll give it a shot. You could google more on the “why”, let’s continue with the tutorial.</p><p>After creating the account, go to your console and select the s3 service in the storage category. On the s3 console, create a new bucket with a proper name that is url friendly, because it will form part of the url to your files. Complete the form and create your new bucket.</p><p>Now that we have a bucket to store our files, let’s write some code.</p><p>Here is our server, with one handler that captures the file uploaded to the route /.</p><pre>package main</pre><pre>import (<br>   &quot;fmt&quot;<br>   &quot;log&quot;<br>)</pre><pre>func handler(w http.ResponseWriter, r *http.Request) {<br>  maxSize := int64(1024000) // allow only 1MB of file size</pre><pre>  err := r.ParseMultipartForm(maxSize)<br>  if err != nil {<br>    log.Println(err)<br>    fmt.Fprintf(w, &quot;Image too large. Max Size: %v&quot;, maxSize)<br>    return<br>  }</pre><pre>  file, fileHeader, err := r.FormFile(&quot;profile_picture&quot;)<br>  if err != nil {<br>    log.Println(err)<br>    fmt.Fprintf(w, &quot;Could not get uploaded file&quot;)<br>    return<br>  }<br>  defer file.Close()</pre><pre>  // create an AWS session which can be<br>  // reused if we&#39;re uploading many files<br>  s, err := session.NewSession(&amp;aws.Config{<br>  Region: aws.String(&quot;us-east-2&quot;),<br>  Credentials: credentials.NewStaticCredentials(<br>    &quot;secret-id&quot;, // id<br>    &quot;secret-key&quot;,   // secret<br>    &quot;&quot;),  // token can be left blank for now<br>  })<br>  if err != nil {<br>    fmt.Fprintf(w, &quot;Could not upload file&quot;)<br>  }</pre><pre>  fileName, err := UploadFileToS3(s, file, fileHeader)<br>  if err != nil {<br>    fmt.Fprintf(w, &quot;Could not upload file&quot;)<br>  }</pre><pre>  fmt.Fprintf(w, &quot;Image uploaded successfully: %v&quot;, fileName)<br>}</pre><pre>func main() {<br>  http.HandleFunc(&quot;/&quot;, handler)<br>  log.Println(&quot;Upload server started&quot;)<br>  log.Fatal(http.ListenAndServe(&quot;:8080&quot;, nil))<br>}</pre><p>Before we continue you need to install the aws go sdk package from github. It can be achieved by running this on you terminal:</p><pre>$ go get github.com/aws/aws-sdk-go/...</pre><p>This will install the go sdk on your system, ready to be used in the application.</p><p>Now we have the go sdk we need to use it for uploading the files we captured from request form. We are going to create one extra function that will receive an <em>aws session</em>, a <em>multipart.File</em>, and a <em>multipart.FileHeader</em> objects. This function will upload the file to aws and return the file name and an <em>error</em> if there was any. We will also update our handler to call the function and return the file url to the user.</p><p>Here is what the code now looks like:</p><pre>package main<br><br>import (<br>	&quot;net/http&quot;<br>	&quot;log&quot;<br>	&quot;fmt&quot;<br>	&quot;mime/multipart&quot;<br>	&quot;bytes&quot;<br>	&quot;path/filepath&quot;<br>	<br>	&quot;github.com/globalsign/mgo/bson&quot;<br>	&quot;github.com/aws/aws-sdk-go/aws&quot;<br>	&quot;github.com/aws/aws-sdk-go/aws/credentials&quot;<br>	&quot;github.com/aws/aws-sdk-go/aws/session&quot;<br>	&quot;github.com/aws/aws-sdk-go/service/s3&quot;<br>)<br><br><br><br>// UploadFileToS3 saves a file to aws bucket and returns the url to // the file and an error if there&#39;s any<br>func UploadFileToS3(s *session.Session, file multipart.File, fileHeader *multipart.FileHeader) (string, error) {<br>  // get the file size and read<br>  // the file content into a buffer<br>  size := fileHeader.Size<br>  buffer := make([]byte, size)<br>  file.Read(buffer)<br><br>  // create a unique file name for the file<br>  tempFileName := &quot;pictures/&quot; + bson.NewObjectId().Hex() +                      filepath.Ext(fileHeader.Filename)<br>	<br>  // config settings: this is where you choose the bucket,<br>  // filename, content-type and storage class of the file<br>  // you&#39;re uploading<br>  _, err := s3.New(s).PutObject(&amp;s3.PutObjectInput{<br>     Bucket:               aws.String(&quot;test-bucket&quot;),<br>     Key:                  aws.String(tempFileName),<br>     ACL:                  aws.String(&quot;public-read&quot;),// could be private if you want it to be access by only authorized users<br>     Body:                 bytes.NewReader(buffer),<br>     ContentLength:        aws.Int64(int64(size)),<br>     ContentType:        aws.String(http.DetectContentType(buffer)),<br>     ContentDisposition:   aws.String(&quot;attachment&quot;),<br>     ServerSideEncryption: aws.String(&quot;AES256&quot;),<br>     StorageClass:         aws.String(&quot;INTELLIGENT_TIERING&quot;),<br>  })<br>  if err != nil {<br>     return &quot;&quot;, err<br>  }<br><br>  return tempFileName, err<br>}<br><br>func handler(w http.ResponseWriter, r *http.Request) {<br>	maxSize := int64(1024000) // allow only 1MB of file size<br><br>	err := r.ParseMultipartForm(maxSize)<br>	if err != nil {<br>	   log.Println(err)<br>	   fmt.Fprintf(w, &quot;Image too large. Max Size: %v&quot;, maxSize)<br>	   return<br>	}<br><br>	file, fileHeader, err := r.FormFile(&quot;profile_picture&quot;)<br>	if err != nil {<br>		log.Println(err)<br>		fmt.Fprintf(w, &quot;Could not get uploaded file&quot;)<br>		return<br>	}<br>	defer file.Close()<br><br>	// create an AWS session which can be<br>	// reused if we&#39;re uploading many files<br>	s, err := session.NewSession(&amp;aws.Config{<br>		Region: aws.String(&quot;us-east-2&quot;),<br>		Credentials: credentials.NewStaticCredentials(<br>			&quot;secret-id&quot;, // id<br>			&quot;secret-key&quot;,   // secret<br>			&quot;&quot;),  // token can be left blank for now<br>	})<br>	if err != nil {<br>		fmt.Fprintf(w, &quot;Could not upload file&quot;)<br>	}<br><br>	fileName, err := UploadFileToS3(s, file, fileHeader)<br>	if err != nil {<br>		fmt.Fprintf(w, &quot;Could not upload file&quot;)<br>	}<br><br>	fmt.Fprintf(w, &quot;Image uploaded successfully: %v&quot;, fileName)<br>}<br><br>func main() {<br>	http.HandleFunc(&quot;/&quot;, handler)<br>	log.Println(&quot;Upload server started&quot;)<br>	log.Fatal(http.ListenAndServe(&quot;:8080&quot;, nil))<br>}</pre><p>As you can see from the complete code, the <em>UploadFileToS3() </em>receives the file size and creates a new buffer with the file size and reads the content of the file to the buffer. Next a random file name is generated to be stored on the aws bucket (You don’t want file names clashing…), and the extension of the file is appended to the end of the filename.</p><p>Next, we create a new S3 bucket instance from the session passed to the function and pass some information to the PutObject function that takes in a PutObjectInput type. The PutObjectInput type sets up the information needed to add the file to the bucket. These information includes the name of the bucket, which is the name of the bucket we created earlier in the aws S3 console, the <em>key, </em>which holds the name of the file, ACL is the type of permission given to the file (it can be <em>public-read </em>or <em>private</em> or any other permissions listed <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl"><strong>here</strong></a>), then the body which is the actual content of the file in the buffer and then the size of the file. Make sure to pass the actual size of the file.</p><p>The upload function receives a session, let’s talk about it.</p><p>We are creating a session which can be reused every time we want to upload a file, hence we are passing it to the upload function. Creating the session requires some credentials like the bucket region, the secret id, and the secret key. These can be obtained from the aws IAM console. If you don’t know how to generate it read <a href="https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccessKey.html"><strong>this</strong></a>.</p><p>These credentials are passed to the session.NewSession() as an aws.Config values. this session can now be passed to the upload function.</p><p>Here is a link to the <a href="https://github.com/spankie/aws-upload"><strong>complete code</strong></a>. If it helped you, please don’t forget to clap, so others will be able to see it. (Tip: you can clap up to 50 times 👏🏽)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2612bea70dd8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spankie/upload-images-to-aws-s3-bucket-in-a-golang-web-application-2612bea70dd8">Upload images to AWS S3 bucket in a golang web application</a> was originally published in <a href="https://medium.com/spankie">Spankie’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I love mithril.js]]></title>
            <link>https://medium.com/spankie/why-i-love-mithril-js-bb74f9aa4dab?source=rss-27519e23f515------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb74f9aa4dab</guid>
            <category><![CDATA[js]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mithriljs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Odohi David]]></dc:creator>
            <pubDate>Sun, 21 Oct 2018 14:02:54 GMT</pubDate>
            <atom:updated>2019-01-11T14:52:58.408Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting started with mithril.js</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*RaHKi0hV80bK6iJZ6edKQQ.jpeg" /><figcaption>mithril.js</figcaption></figure><p>First of all what is mithril.js? Mithril.js is a javascript framework for building Single Page Applications (SPAs). One thing that makes mithril standout for me is it being lightweight, compared to it’s other popular counterparts; React, Angular and Vue.js, Mithril is just 8kb (&lt; 8kb gzip) (v.1.1.6).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*y4q85R7nxxhlARgIzKXC4Q.png" /><figcaption>here is a screenshot of their benchmark found in their website.</figcaption></figure><p>Mithril has a very shallow learning curve, this is largely due to the concise documentation which I find very detailed. Pardon me I might be sounding like a real fan boy here. 🙈</p><p>A simple application with built in routing (<em>*Winks at React*</em>) is as simple as this:</p><pre>var Splash = {<br>    view: function() {<br>        return m(&quot;a&quot;, {href: &quot;#!/hello&quot;}, &quot;Enter!&quot;)<br>    }<br>}</pre><pre>m.route(document.body, &quot;/splash&quot;, {<br>    &quot;/splash&quot;: Splash<br>})</pre><blockquote>My reaction at first was <strong><em>“What are those!”</em></strong> m(&quot;a&quot;, {href: &quot;#!/hello&quot;}, &quot;Enter!&quot;)</blockquote><p>Well, mithril has its compiled representation of JSX called hyperscript, according to them, it is designed to be readable and used as-is, because JSX requires a lot of tooling to work with and maintain in mithril. Personally I prefer using JSX, ’cause of it’s semblance with good ol’ HTML. I can practically do pretty much anything in JSX as I can do in hyperscript, with a little dev setup tho. To use JSX with mithril, one will need babel and babel plugin (babel-plugin-transform-react-jsx) to compile it. It can either be compiled with the babel cli tool or with in webpack.</p><p>The documentation for mithril can be found <a href="https://mithril.js.org/"><em>here</em></a><em>. </em>It’s very easy to understand and get started with.</p><p>Apart from setting up tooling to compile JSX, getting started with building an app with mithril is quite simple. You can manage your application state without too much complexity and easily without redux and the likes for a number of a reasonably large application. But that does not diminish the importance of having redux in your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb74f9aa4dab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spankie/why-i-love-mithril-js-bb74f9aa4dab">Why I love mithril.js</a> was originally published in <a href="https://medium.com/spankie">Spankie’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>