<?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 Satadeep Dasgupta on Medium]]></title>
        <description><![CDATA[Stories by Satadeep Dasgupta on Medium]]></description>
        <link>https://medium.com/@satadeepdasgupta?source=rss-f658f9a6a27a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*72FejY-CwqvsE1bjuMtGzQ.jpeg</url>
            <title>Stories by Satadeep Dasgupta on Medium</title>
            <link>https://medium.com/@satadeepdasgupta?source=rss-f658f9a6a27a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:43:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@satadeepdasgupta/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[The Windows Machine Doesn't Have fork(). So We Built One.]]></title>
            <link>https://faun.pub/the-windows-machine-doesnt-have-fork-so-we-built-one-b10e1357aa4f?source=rss-f658f9a6a27a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b10e1357aa4f</guid>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[system-programming]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Satadeep Dasgupta]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 20:56:25 GMT</pubDate>
            <atom:updated>2026-07-03T21:43:36.970Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9JqEciEQzIwHGv3buRKSgQ.png" /></figure><blockquote>Recreating Redis-style Copy-on-Write snapshots on Windows using hardware exceptions and Vectored Exception Handlers</blockquote><p>Let me tell you a story about a machine that pretends.</p><p>If you’ve ever used Redis, you’ve probably noticed something almost magical about it: you can tell it to save a multi-gigabyte dataset to disk, and it just… does it, in the background, without ever making you wait. You keep reading and writing keys the whole time. No freeze, no stutter, nothing.</p><p>For years I used this feature without really asking how it worked. It felt like one of those things you’re not supposed to look at too closely, like a magic trick — you enjoy it more if you don’t know where the extra card came from. But eventually curiosity got the better of me, and once I actually looked underneath, I found something I liked even more than the trick itself: a genuinely clever piece of engineering that Linux gives you almost for free, and that Windows refuses to give you at all.</p><p>This article is about the part where Windows refuses, and what I did about it.</p><p>Grab that coffee. This one’s going to take a while, because I want to actually explain the intricacies this time, not just wave at them.</p><h3>Part 1: How Redis Cheats on Linux</h3><p>Here’s the trick. When Redis wants to save a snapshot, it doesn’t copy your data. Copying gigabytes of memory would take too long and would need to lock everything while it happens. Instead, on Linux, Redis calls a function named fork().</p><p>fork() is a strange and wonderful system call. It takes the currently running process and duplicates it - creates a full second copy, right down to every variable, every open file, every byte of memory. And it&#39;s supposed to be slow, because copying all of a process&#39;s memory should take real time. Except it isn&#39;t slow. It&#39;s nearly instant, even for a process using tens of gigabytes of RAM.</p><p>How?</p><p>The operating system lies to you. It doesn’t actually copy the memory. It copies the <em>map</em> — the address book that tells the CPU which physical memory each virtual address points to — and then it marks every one of those pages as “look, but don’t touch.” Both the parent and the child process are, for a brief shining moment, pointing at the exact same physical memory. Nothing has actually been duplicated. It’s a con, and a beautiful one.</p><p>The moment either process tries to <em>write</em> to one of those shared pages, the hardware itself notices. The CPU raises a fault, the kernel catches it, and <em>only then</em> — only for that one 4-kilobyte page that got written to — does it actually make a private copy for the writer. This is Copy-on-Write, or COW, and it’s why fork() for a snapshot is nearly free: you only pay the copying cost for pages that actually change, and you pay it in tiny, lazy installments instead of one giant bill up front.</p><p>So the child process, frozen at the exact instant of the fork, calmly writes every page to disk — the true, unchanging pages directly, and any page the parent has since modified via its own private copy. The parent, meanwhile, never stops. It just keeps writing, blissfully unaware that some of its pages are quietly being duplicated behind its back.</p><p>It’s elegant because the CPU is doing almost all the hard work. The kernel just tells the memory management unit “protect these pages” and gets out of the way.</p><p>Now here’s the sentence that started this whole project:</p><p><strong>Windows does not have </strong><strong>fork().</strong></p><p>There is no equivalent syscall that duplicates a process and gives you this lazy, hardware-assisted copy-on-write for free. If you want this behavior on Windows, you have to build the lie yourself.</p><h3>Part 2: If the OS Won’t Lie For You, Lie Yourself</h3><p>So I sat with this problem for a while. If Windows won’t play MMU tricks on my behalf to fake a whole second process, could I fake something narrower — not a whole process, just the copy-on-write <em>behavior</em>, applied only to the one arena of memory my database actually cares about?</p><p>It turns out you can, and the ingredients are things Windows has had for decades, just never assembled this way for this purpose:</p><ul><li>VirtualAlloc and VirtualProtect, which let you control memory permissions yourself, page by page.</li><li>Vectored Exception Handlers (VEH), which let your own application code intercept hardware faults — the same kind of fault that fork()&#39;s copy-on-write relies on - before Windows decides what to do with them.</li><li>Atomics, to make sure that when multiple threads are hammering the database at once, nobody sees a half-finished write.</li></ul><p>Here’s the plan, in plain language before we touch any code:</p><p>I put <em>everything</em> the database owns — every key, every value, the whole hash table — into one giant slab of memory, allocated up front. Call it the arena. When it’s time to take a snapshot, instead of forking the whole process, I simply tell Windows: “this entire arena is now read-only.” Any thread that tries to write a key after that point is going to hit a wall — literally, a hardware access violation — the instant it tries.</p><p>That’s not a bug. That’s the trap working exactly as intended.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hp1uo3GbADgjTMa0" /></figure><p>Take a second with that diagram, because there’s something subtle in it that trips people up the first time: the shadow copy holds the <em>old</em> data, not the new data. The writer’s fresh value goes straight into the live page after the handler lets it through. It’s the background snapshotter that reads from the shadow buffer, precisely because it wants to see the world as it was at the moment BGSAVE began, not as it is now. The live arena keeps moving forward; the shadow pages are little frozen photographs of the pages that dared to change.</p><h3>Part 3: What Actually Happens Inside That Handler</h3><p>Let’s slow down even further, because “the CPU raises a fault and we catch it” is doing a lot of hand-waving, and I promised no more hand-waving.</p><p>When a thread executes a mov instruction that writes to a read-only page, the CPU doesn&#39;t ask permission first - it just tries, fails at the hardware level, and interrupts. Windows catches this interrupt and, because we registered a Vectored Exception Handler with AddVectoredExceptionHandler, it calls our function <em>before</em> it decides whether to crash the process. Our handler gets a structure telling us exactly which address was touched and whether it was a read or a write attempt.</p><p>And here’s the detail that matters most, the one that will bite you if you don’t respect it: <strong>the thread that caused the fault is frozen, mid-instruction, for as long as our handler is running.</strong> It hasn’t crashed. It’s paused, like someone caught with one foot in the air, waiting for us to either let it land or tell it to trip.</p><p>This has a wonderful consequence and a nasty trap, and they’re the same fact seen from two angles.</p><p>The wonderful consequence: we get to safely memcpy the page&#39;s contents into a shadow buffer <em>before</em> letting the write happen, and no other thread can be modifying that same page at that instant, because the entire arena is marked read-only - every thread that tries to write anything anywhere in the arena hits the same wall and waits in line for a handler.</p><p>The nasty trap: whatever <em>else</em> that frozen thread was doing when it got interrupted is now also frozen. If it happened to be holding a lock — say, a lock inside the C runtime’s memory allocator, because it called malloc two lines earlier for something completely unrelated - that lock is now held forever, from our handler&#39;s point of view. And if our handler then tries to allocate memory using that same allocator, to get space for the shadow page, we ask for a lock that will never be released, because the only thread that could release it is the one we&#39;re blocking on.</p><p>Two threads, each waiting on the other, neither one able to move. A deadlock, and a particularly sneaky one, because it doesn’t happen every time — only on the unlucky occasion when the fault lands on a thread that happens to be inside the allocator at that exact moment. It might work fine for an hour of testing and then lock up in production.</p><p>The fix, once you see the shape of the trap, is almost obvious: <strong>never call the general-purpose allocator from inside the handler.</strong> Go around it entirely. Ask the operating system directly for a page of memory, the same way the arena itself was allocated:</p><pre>void* shadow = VirtualAlloc(nullptr, VEYR_PAGE_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);</pre><p>VirtualAlloc doesn&#39;t go anywhere near malloc&#39;s locks. It talks straight to the kernel&#39;s memory manager, which is a different piece of machinery entirely, with its own locking discipline that doesn&#39;t intersect with ours. This isn&#39;t a quirk of C++, by the way - I want to be very clear about that, because I originally assumed it was a Rust-versus-C++ thing and I was wrong. The deadlock has nothing to do with which language you&#39;re in. It has to do with <em>which allocator</em> you call from inside a handler where an arbitrary thread might be frozen holding an arbitrary lock. Rust&#39;s global allocator has the exact same hazard if you call into it from a signal-like context; you avoid it in Rust exactly the way you avoid it here, by dropping down to the raw OS allocation call and never touching the language&#39;s normal heap while the handler is running.</p><p>Here’s the full handler, now that you know why every line is the way it is:</p><pre>static LONG WINAPI veh_handler(EXCEPTION_POINTERS* info) { if (info-&gt;ExceptionRecord-&gt;ExceptionCode != EXCEPTION_ACCESS_VIOLATION) return EXCEPTION_CONTINUE_SEARCH; // not our problem, pass it along ULONG_PTR rw = info-&gt;ExceptionRecord-&gt;ExceptionInformation[0]; ULONG_PTR fault_addr = info-&gt;ExceptionRecord-&gt;ExceptionInformation[1]; if (rw != 1 || !g_arena) return EXCEPTION_CONTINUE_SEARCH; // it was a read fault, or we&#39;re not even armed auto arena_start = reinterpret_cast&lt;uintptr_t&gt;(g_arena-&gt;base()); auto arena_end = arena_start + g_arena-&gt;size(); if (fault_addr &lt; arena_start || fault_addr &gt;= arena_end) return EXCEPTION_CONTINUE_SEARCH; // some other, unrelated fault // Which 4KB page owns this address? uintptr_t page_addr = fault_addr &amp; ~(VEYR_PAGE_SIZE - 1); size_t page_index = (page_addr - arena_start) / VEYR_PAGE_SIZE; // Go straight to the OS. Never the CRT heap. This line is the whole ballgame. void* shadow = VirtualAlloc(nullptr, VEYR_PAGE_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (!shadow) return EXCEPTION_CONTINUE_SEARCH; // Copy it NOW, while it&#39;s still frozen and read-only. This is our photograph. std::memcpy(shadow, reinterpret_cast&lt;void*&gt;(page_addr), VEYR_PAGE_SIZE); // Two threads could fault on the same page at nearly the same moment. // Whoever gets here first wins; the loser&#39;s copy is thrown away. void* expected = nullptr; if (!g_shadow.entries[page_index].compare_exchange_strong( expected, shadow, std::memory_order_acq_rel)) { VirtualFree(shadow, 0, MEM_RELEASE); } // Let the page breathe again, and send the frozen thread on its way. DWORD old_protect; VirtualProtect(reinterpret_cast&lt;LPVOID&gt;(page_addr), VEYR_PAGE_SIZE, PAGE_READWRITE, &amp;old_protect); return EXCEPTION_CONTINUE_EXECUTION; }</pre><p>Notice the order of operations one more time, because it’s the single most important sequencing decision in the whole design: <strong>copy first, unprotect second.</strong> If you flip those two lines, you’ve built a race condition into your own snapshot mechanism. The instant you call VirtualProtect to make the page writable again, <em>every other thread</em> waiting on that same page is free to start mutating it - and if your memcpy hasn&#39;t finished yet, you might photograph a page that&#39;s half old data and half new data. Your &quot;point-in-time&quot; snapshot would contain moments that never actually existed. Order matters here in a way that&#39;s easy to get right by accident once and then forget why it mattered.</p><h3>Part 4: A Hash Table That Never Blocks</h3><p>Snapshotting solved, but there’s a second problem lurking underneath: even without any of this COW machinery, how fast can the map itself go? If every GET and SET has to fight over a single lock, none of the cleverness above matters - you&#39;ll bottleneck long before you ever call BGSAVE.</p><p>The obvious first attempt is std::unordered_map wrapped in a std::shared_mutex. It works, and it&#39;s a perfectly reasonable thing to reach for first. But under real concurrent load - a hundred clients all hammering keys at once - you can feel the ceiling. Every write needs exclusive access, so writers queue up behind each other no matter how many CPU cores you have sitting idle.</p><p>So instead, I gave every slot in the table a plain atomic pointer:</p><pre>struct Slot { std::atomic&lt;Entry*&gt; entry{nullptr}; };</pre><p>No lock. Just a pointer that can be swapped atomically. But this immediately raises a question that’s worth sitting with: if there’s no lock, what stops a reader from grabbing a pointer to an entry that’s <em>currently</em> being written — reading a key that’s valid but a value that’s still half-formed?</p><p>This is called a Time-Of-Check to Time-Of-Use race, and the fix is almost philosophical: don’t let anything be half-formed in the first place. Bundle the key and the value into a single, immutable block, and only ever publish it to readers once it’s completely finished:</p><pre>struct Entry { uint32_t key_len; uint32_t val_len; char data[1]; // key bytes, then value bytes, back to back };</pre><p>An Entry, once built, never changes. It&#39;s not edited in place - ever. When a key gets updated, we don&#39;t touch the old Entry at all. We build a brand new one, complete and fully formed off to the side, and only then do we atomically swap the slot&#39;s pointer to point at it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/0*MQYH6gYafKs0nctx" /></figure><p>The trick is that a reader can <em>never</em> observe a pointer to something half-built, because nothing half-built is ever published. It’s either the fully-formed old version or the fully-formed new version, and the switch between them happens as one indivisible pointer write. No lock, no race, no torn reads.</p><p>The full SET path looks like this once you put it together:</p><pre>bool map_set(const char* key, uint32_t key_len, const char* val, uint32_t val_len) { size_t idx = fnv1a(key, key_len) % SLOT_COUNT; for (size_t i = 0; i &lt; MAX_PROBE_DISTANCE; ++i) { Slot&amp; slot = g_slots[idx]; Entry* existing = slot.entry.load(std::memory_order_acquire); if (existing == nullptr) { Entry* e = make_entry(key, key_len, val, val_len); Entry* expected = nullptr; if (slot.entry.compare_exchange_strong(expected, e, std::memory_order_acq_rel)) return true; existing = slot.entry.load(std::memory_order_acquire); } if (existing-&gt;key_len == key_len &amp;&amp; std::memcmp(existing-&gt;key_data(), key, key_len) == 0) { Entry* e = make_entry(key, key_len, val, val_len); slot.entry.store(e, std::memory_order_release); return true; } idx = (idx + 1) % SLOT_COUNT; // linear probe to the next slot } return false; }</pre><p>Now, I promised to be honest about intricacies, so here’s one I glossed over the first time I wrote about this: <strong>what happens to the old </strong><strong>Entry after it gets swapped out?</strong></p><p>The uncomfortable answer is — nothing, currently. It just sits there in memory, orphaned, because we can’t safely free it. A reader might have loaded a pointer to it a microsecond before the swap and could still be reading from it right now. Freeing it immediately would be a use-after-free waiting to happen. The entries are carved out of a bump arena, so for the lifetime of a single benchmark run this is invisible — the arena just grows. But under sustained real-world traffic, with the same handful of keys getting overwritten millions of times, this is a genuine memory leak. The proper fix is something like hazard pointers or epoch-based reclamation, where you track which entries no reader could possibly still be touching before you reclaim them. I haven’t built that yet. I want to say that plainly rather than bury it, because it’s the difference between “this is a fun demonstration of a technique” and “this is a database.”</p><h3>Part 5: Putting It on the Scale</h3><p>So — after all of that, does the trick actually pay off? I built Veyr as a small RESP server, wired up just GET and SET, sitting on top of everything described above, and ran it against redis-benchmark on the same machine as Memurai, a mature, full-featured Redis-compatible server for Windows.</p><p>I want to frame this comparison carefully, because it’s tempting to read a benchmark like this as “Veyr beats Redis,” and that’s not really what’s being measured. Memurai implements the entire Redis command surface, persistence formats, replication, ACLs — everything a real deployment leans on. Veyr implements two commands and the memory trick that makes them fast. Of course the narrow, purpose-built thing is faster at the narrow thing it does. That’s not a scandal, it’s the whole point of building a minimal prototype: to find out what the <em>technique</em> costs, without the weight of everything else a real server has to carry.</p><p>With that said, here’s what the same machine, same benchmark, back to back, actually showed:</p><pre>redis-benchmark.exe -h 127.0.0.1 -p &lt;port&gt; -c 100 -P 200 -t get,set -n 1000000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJj-kgJRemytfmGxgKmoLA.png" /></figure><p>The raw numbers are one thing, but the latency percentiles told me more about <em>why</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*RBQWgYX_1NZebeLG" /></figure><p>Look at how differently these two curves climb. Veyr is nearly a step function — almost nothing finishes by 2ms, and then the overwhelming majority finish by 3ms, done by 4ms. Memurai’s curve is a long, gradual slope, still only half finished at 9ms and not wrapping up until 12ms. A steep, early curve like Veyr’s usually means requests are moving through a short, uncontested path — little to no waiting on locks, few context switches, not much bookkeeping between &quot;message arrived&quot; and &quot;message answered.&quot; A long gradual tail like Memurai’s is the signature of a busier system: more work per request, more opportunities for one request to end up waiting behind another.<br>Neither shape is wrong. They’re two servers doing very different amounts of work per request, and the latency curve is basically a photograph of that difference.<br>A few honest notes on the benchmark itself, because a number without its context is just a number wearing a costume: these are single runs, not medians across several trials, so treat them as directional rather as gospel. I didn’t check whether Memurai had any background persistence running during its measurement window, which could add latency unrelated to its core request path. And -P 200 — two hundred pipelined requests per connection — flatters throughput numbers generally, since it amortizes round-trip cost heavily; it’s a legitimate way to measure raw engine speed, but it’s not the same as measuring single-request latency under realistic traffic.</p><h3>Where That Leaves Things</h3><p>What I set out to answer was a fairly narrow question: is it possible, on a platform that gives you none of fork()&#39;s tricks, to build the same lazy, hardware-assisted copy-on-write behavior yourself, entirely in user space? And the answer, it turns out, is yes - with a vectored exception handler standing in for the kernel&#39;s fault handler, VirtualProtect standing in for the page tables, and a bit of discipline about never touching a locking allocator from inside a frozen thread&#39;s shadow.</p><p>What I haven’t answered, and want to be honest about, is whether this is ready to be a database rather than a demonstration of one idea done well. The orphaned entries with no reclamation path, the fixed slot count with no resizing, the two-command surface — these are the real remaining work, and they’re not small. But the core trick — the one Windows refused to give me for free — works, and works fast.</p><p>If you want to see the whole thing end to end, the source is here: <a href="https://github.com/satadeep3927/veyr">satadeep3927/veyr</a></p><h3>One Last Thing</h3><p>Remember how I said fork() felt like a magic trick I didn’t want to look at too closely? That’s not true anymore, for me. I’ve seen the wires now — the page fault, the frozen thread, the shadow buffer standing in for a photograph nobody else gets to touch until it’s finished. It’s not less impressive up close. If anything it’s more impressive, because now I know exactly how much care it took to make something this fast look effortless.<br>Veyr isn’t going to replace anything. It was never meant to. It was a question I needed to answer with my own hands before I’d trust the answer from anyone else: can this be done on a platform that was never built for it? Now that I know it can, the harder and more interesting work starts — building something that keeps this speed but earns the right to be called a database. That’s a different article, for a different day.<br>Go pour yourself another coffee. You earned it if you made it this far.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b10e1357aa4f" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/the-windows-machine-doesnt-have-fork-so-we-built-one-b10e1357aa4f">The Windows Machine Doesn&#39;t Have fork(). So We Built One.</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BUILDING A REST API WITH GO AND SQLITE(PART 2)]]></title>
            <link>https://faun.pub/building-a-rest-api-with-go-and-sqlite-part-2-8a962b09bd6b?source=rss-f658f9a6a27a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a962b09bd6b</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Satadeep Dasgupta]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 09:31:30 GMT</pubDate>
            <atom:updated>2024-03-06T18:45:40.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JDJZzXLTgRXPNLm-H2WKsw.jpeg" /><figcaption>TNANKS TO DALL-E 4</figcaption></figure><p><strong>Building on the foundation laid in the first part of our series on creating a REST API with Go and SQLite, we now turn our attention to fleshing out the functionality of our Blog API. We’ll focus on implementing the remaining CRUD operations: creating, updating, and deleting blog posts. Additionally, we’ll introduce error handling and validation to ensure our API behaves correctly and securely.</strong></p><h3>Implementing CRUD Operations</h3><h4>Creating a New Blog Post</h4><p>To allow users to add new blog posts, we’ll implement a createBlog function that handles POST requests. This function will parse the request body to a Blog struct, validate the input, and then insert the new blog post into the SQLite database.</p><pre>func createBlog(c *gin.Context) {<br>    // Parse text fields first<br>    author := c.PostForm(&quot;author&quot;)<br>    title := c.PostForm(&quot;title&quot;)<br>    content := c.PostForm(&quot;content&quot;)<br><br>    // Handle the file upload<br>    file, err := c.FormFile(&quot;image&quot;)<br>    if err != nil {<br>        c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>        return<br>    }<br><br>    // Generate a unique file name for storage to avoid name collisions<br>    // This example uses a UUID, but you can choose your method<br>    newFileName := uuid.New().String() + filepath.Ext(file.Filename)<br><br>    // Define your path where you want to store the image<br>    path := &quot;uploads/&quot; + newFileName<br><br>    // Save the file to the server<br>    if err := c.SaveUploadedFile(file, path); err != nil {<br>        c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: err.Error()})<br>        return<br>    }<br><br>    // Now, path stores the reference to the image file, which you can insert into the database<br><br>    // Insert the new blog post into the database, including the image path<br>    stmt, err := models.DB.Prepare(&quot;INSERT INTO blogs(author, title, content, image, created_at) VALUES(?,?,?,?,CURRENT_DATE)&quot;)<br>    if err != nil {<br>        c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: err.Error()})<br>        return<br>    }<br>    _, err = stmt.Exec(author, title, content, path)<br>    if err != nil {<br>        c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: err.Error()})<br>        return<br>    }<br><br>    c.JSON(http.StatusCreated, gin.H{&quot;message&quot;: &quot;Blog post created successfully!&quot;, &quot;imagePath&quot;: path})<br>}</pre><h4>Updating a Blog Post</h4><p>To update an existing blog post, we’ll need an updateBlog function. This function will extract the blog post ID from the URL, parse the request body, and update the blog post in the database.</p><pre>func updateBlog(c *gin.Context) {<br>    id := c.Param(&quot;id&quot;)<br><br>    // Parse text fields<br>    author := c.PostForm(&quot;author&quot;)<br>    title := c.PostForm(&quot;title&quot;)<br>    content := c.PostForm(&quot;content&quot;)<br><br>    // Handle the file upload (if a new file is provided)<br>    file, err := c.FormFile(&quot;image&quot;)<br>    var path string<br>    if err == nil { // This means a new file is uploaded<br>        // Generate a unique file name for storage to avoid name collisions<br>        newFileName := uuid.New().String() + filepath.Ext(file.Filename)<br><br>        // Define your path where you want to store the image<br>        path = &quot;uploads/&quot; + newFileName<br><br>        // Save the file to the server<br>        if err := c.SaveUploadedFile(file, path); err != nil {<br>            c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: err.Error()})<br>            return<br>        }<br>    } else {<br>        // If no new file is uploaded, use the existing image path<br>        // Fetch the current image path from the database (omitted for brevity)<br>        // For example, let&#39;s assume it&#39;s fetched into a variable named `currentImagePath`<br>        currentImagePath := &quot;&quot; // Implement fetching logic here<br>        path = currentImagePath<br>    }<br><br>    // Update the blog post in the database, including the new or existing image path<br>    stmt, err := models.DB.Prepare(&quot;UPDATE blogs SET author=?, title=?, content=?, image=? WHERE id=?&quot;)<br>    if err != nil {<br>        c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: err.Error()})<br>        return<br>    }<br>    _, err = stmt.Exec(author, title, content, path, id)<br>    if err != nil {<br>        c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: err.Error()})<br>        return<br>    }<br><br>    c.JSON(http.StatusOK, gin.H{&quot;message&quot;: &quot;Blog post updated successfully!&quot;, &quot;imagePath&quot;: path})<br>}</pre><h4>Deleting a Blog Post</h4><p>Finally, to allow deletion of blog posts, we’ll implement a deleteBlog function. This function will remove a blog post from the database based on the ID provided in the URL.</p><pre>func deleteBlog(c *gin.Context) {<br>    id := c.Param(&quot;id&quot;)<br><br>    stmt, err := models.DB.Prepare(&quot;DELETE FROM blogs WHERE id = ?&quot;)<br>    if err != nil {<br>        c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: err.Error()})<br>        return<br>    }<br>    _, err = stmt.Exec(id)<br>    if err != nil {<br>        c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: err.Error()})<br>        return<br>    }<br><br>    c.JSON(http.StatusOK, gin.H{&quot;message&quot;: &quot;Blog post deleted successfully!&quot;})<br>}</pre><h4>Serving Image Files</h4><p>To serve image files stored on your server:</p><p>Static File Serving: Configure your Go application to serve static files from the directory where you’re storing uploaded images. With Gin, you can use router.Static(&quot;/uploads&quot;, &quot;./uploads&quot;) to serve files stored in the uploads directory.</p><h4>Functional Overview</h4><p>The three functions discussed — createBlog, updateBlog, and deleteBlog—serve as key components of a RESTful API designed for managing blog posts, including handling text data and image files. Each function is tailored to a specific CRUD (Create, Read, Update, Delete) operation within the context of a blog application using the Go programming language and the Gin web framework. Below is a functional overview of each:</p><h3>1. createBlog</h3><p>Purpose: To create a new blog post in the system.</p><p>Functionality:</p><ul><li>Receive Data: It handles HTTP POST requests containing multipart/form-data, which includes both text fields (like author, title, content) and binary data (an image file).</li><li>Validate and Process Data: The function validates the received data (e.g., checking for required fields, file size, and type constraints). It processes the image by saving it to a server directory and prepares the text data for database insertion.</li><li>Database Interaction: It inserts a new record into the blog posts database, including references to the text data and the path to the saved image.</li><li>Response: On successful creation, it responds with an HTTP status code 201 (Created) and, typically, some information about the created blog post, such as a success message or the post’s ID.</li></ul><h3>2. updateBlog</h3><p>Purpose: To update an existing blog post’s information, including changing its associated image.</p><p>Functionality:</p><ul><li>Receive Data: Similar to createBlog, it handles HTTP POST or PUT requests with multipart/form-data. The request must include the ID of the blog post to update, along with any new text and/or image file.</li><li>Validate and Process Data: It checks the provided data for completeness and validity. If a new image is provided, the function saves the new image, replacing the old one, and updates the text fields as necessary.</li><li>Database Interaction: It updates the specified blog post’s record in the database with the new data. If an image is updated, the reference to the image file (its path) is also updated.</li><li>Response: It returns an HTTP status code indicating the outcome (e.g., 200 OK for success) and, typically, a message or data about the updated blog post.</li></ul><h3>3. deleteBlog</h3><p>Purpose: To remove an existing blog post from the system.</p><p>Functionality:</p><ul><li>Receive Data: This function is triggered by an HTTP DELETE request and expects an identifier (ID) for the blog post to be deleted, usually passed as part of the URL path.</li><li>Database Interaction: It deletes the blog post’s record from the database. Depending on the implementation, it might also involve deleting the associated image file from the server to free up space.</li><li>Response: It responds with an HTTP status code to indicate the result (e.g., 200 OK if the deletion was successful) and possibly a success message or the ID of the deleted post.</li></ul><h4>Error Handling and Validation</h4><p>Throughout our CRUD operations, we’ve introduced basic error handling to ensure our API responds appropriately to various failure scenarios. It’s crucial to validate incoming data to protect against invalid or malicious input. While we’ve omitted detailed validation logic for brevity, you might consider using a package like govalidator or implementing custom validation logic to check the integrity of the data being inserted or updated.</p><h4>Conclusion</h4><p>With the completion of these CRUD operations, our Blog API is now fully functional. Users can create, read, update, and delete blog posts. We’ve also introduced essential error handling and touched upon the importance of validating input data.</p><p>In future articles, we could explore more advanced topics, such as adding authentication to secure our API, deploying our application, or enhancing its performance and scalability.</p><p>Remember, the journey of learning Go and building web APIs doesn’t stop here. Experiment with the code, try adding new features, and most importantly, have fun coding!</p><p>If you found this article helpful, please consider showing your support by clapping 👏 and sharing it with others who might find it useful. Stay tuned for more articles on Go, SQLite, and web development!</p><p>***<strong>A Heartfelt Apology for being too late</strong>***</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*geDH1Og5cKdVY_Ta.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN Developer Community &amp; Get Similar Stories in your Inbox Each Week</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a962b09bd6b" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/building-a-rest-api-with-go-and-sqlite-part-2-8a962b09bd6b">BUILDING A REST API WITH GO AND SQLITE(PART 2)</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BUILDING A REST API WITH GO AND SQLITE(PART 1)]]></title>
            <link>https://faun.pub/building-a-rest-api-with-go-and-sqlite-part-1-97c29ed2f282?source=rss-f658f9a6a27a------2</link>
            <guid isPermaLink="false">https://medium.com/p/97c29ed2f282</guid>
            <category><![CDATA[gin]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Satadeep Dasgupta]]></dc:creator>
            <pubDate>Tue, 17 May 2022 17:49:55 GMT</pubDate>
            <atom:updated>2022-05-18T19:36:57.148Z</atom:updated>
            <content:encoded><![CDATA[<p>Go and SQLite 3 are the best choice for scalable and lightning fast applications. In this article we build a small Web API to understand the basics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rn2WaWK7JvIBjHCxD-NxqA.jpeg" /><figcaption>Image Credit : Pinterest</figcaption></figure><p>There are many options open to build scalable Web APIs but if you need to build scalable, lightning fast web APIs with minimalistic approach, GO and SQLite can be an excellent choice for your next project. Today we’ll build a very simple <strong>Blog API</strong> with these technologies. So, grab a cup of coffee and let’s start. For this lesson we’ll use 3 Technologies</p><ol><li>Go Programming Language</li><li>SQLite Database Engine</li><li>GIN Web Framework</li></ol><h3>GO Programming Language</h3><p>Why I’m choosing GO over Laravel, NodeJs and Python?</p><p>Well, because I need a topic to write a Article and Earn money, LOL!! That sounds logical but not true in this case. Go is as easy as Python and as performant as C++ . Go is preferred as one of the best choice for development due to it’s simplicity and blazing performance.</p><p><strong>✓ </strong>Go is an open source programming language supported by Google</p><p><strong>✓ </strong>Easy to learn and get started with</p><p><strong>✓ </strong>Built-in concurrency and a robust standard library</p><p><strong>✓ </strong>Growing ecosystem of partners, communities, and tools</p><h3>SQLite Database Engine</h3><p>SQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. It is a database, which is zero-configured, which means like other databases you do not need to configure it in your system.</p><p>SQLite engine is not a standalone process like other databases, you can link it statically or dynamically as per your requirement with your application. SQLite accesses its storage files directly.</p><h3>Why SQLite?</h3><p><strong>✓ </strong>SQLite does not require a separate server process or system to operate (serverless).</p><p><strong>✓ </strong>SQLite comes with zero-configuration, which means no setup or administration needed.</p><p><strong>✓ </strong>A complete SQLite database is stored in a single cross-platform disk file.</p><p><strong>✓ </strong>SQLite is very small and light weight, less than 400KiB fully configured or less than 250KiB with optional features omitted.</p><h3>GIN Web Framework</h3><p>Gin is a web framework written in Go (Golang). It features a martini-like API with performance that is up to 40 times faster thanks to <a href="https://github.com/julienschmidt/httprouter">httprouter</a>. If you need performance and good productivity, you will love Gin.</p><h3>Prerequisites</h3><ul><li>Install Go programming language from <a href="https://go.dev/dl/">here</a>. (If you haven’t already installed)</li><li>Postman Software to Test APIs. You can download it from <a href="https://www.postman.com/downloads/postman-agent/">here</a>.</li><li>We’ll use <a href="https://sqliteonline.com/">sqliteonline.com</a> as our SQLite Client.</li><li>A Text Editor or Integrated Development Environment. For this tutorial I’ll use Visual Studio Code. You can download it for free from <a href="https://code.visualstudio.com/">here</a></li></ul><h3>Let’s Initiate the Project</h3><p>Create a Directory in your hard drive. Now, Open your command prompt or terminal here. For Windows you can use right click with shift to open context menu and then choose open with Powershell option.</p><p>Paste the following code in your Powershell and press Enter.</p><pre>go mod init demo.com/blog</pre><p>It will initiate a Go project. In the next step we will install few required libraries for our application.</p><pre>go get -u github.com/mattn/go-sqlite3<br>go get -u github.com/gin-gonic/gin</pre><p>We’ll create a new file named main.goand add following code.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528251%252C251%252C251%252C1%2529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dauto%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dpackage%252520main%25250A%25250Aimport%252520%2528%25250A%252509%252522github.com%25252Fgin-gonic%25252Fgin%252522%25250A%2529%25250A%25250Afunc%252520main%2528%2529%252520%25257B%25250A%25250A%252520%252520%25250A%25257D%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528251%25252C251%25252C251%25252C1%252529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dauto%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dpackage%25252520main%2525250A%2525250Aimport%25252520%252528%2525250A%25252509%25252522github.com%2525252Fgin-gonic%2525252Fgin%25252522%2525250A%252529%2525250A%2525250Afunc%25252520main%252528%252529%25252520%2525257B%2525250A%2525250A%25252520%25252520%2525250A%2525257D%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad5285fd7287575ec5bf19f62743af4d/href">https://medium.com/media/ad5285fd7287575ec5bf19f62743af4d/href</a></iframe><p>Now Save it.</p><h3>Let’s Define Routes</h3><p>We’ll set up our routes without real database connection. This will let us focus on routes and handlers rather than database. Once we complete the router setup we’ll integrate them with the database.</p><p>An ideal router takes incoming requests and maps them to the handler function. For this project we’ll set up four routes for CRUD(CREATE, READ, UPDATE, DELETE) operations. Let’s add the following code inside main()function.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528251%252C251%252C251%252C1%2529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dr%252520%25253A%25253D%252520gin.Default%2528%2529%25250A%25250A%25252F%25252F%252520API%252520v1%25250Arouter%252520%25253A%25253D%252520r.Group%2528%252522%25252Fblogs%252522%2529%25250A%25257B%25250A%252509router.POST%2528%252522%25252Fcreate%252522%25252C%252520postBlog%2529%25250A%252509router.GET%2528%252522%25252F%252522%25252C%252520readBlog%2529%25250A%252509router.POST%2528%252522%25252Fupdate%25252F%25253Aid%252522%25252C%252520updateBlog%2529%25250A%252509router.GET%2528%252522%25252Fdelete%25252F%25253Aid%252522%25252C%252520deleteBlog%2529%25250A%25257D%25250A%25250A%25252F%25252F%252520By%252520default%252520it%252520serves%252520on%252520%25253A8080%25250Ar.Run%2528%2529&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528251%25252C251%25252C251%25252C1%252529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%25252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dr%25252520%2525253A%2525253D%25252520gin.Default%252528%252529%2525250A%2525250A%2525252F%2525252F%25252520API%25252520v1%2525250Arouter%25252520%2525253A%2525253D%25252520r.Group%252528%25252522%2525252Fblogs%25252522%252529%2525250A%2525257B%2525250A%25252509router.POST%252528%25252522%2525252Fcreate%25252522%2525252C%25252520postBlog%252529%2525250A%25252509router.GET%252528%25252522%2525252F%25252522%2525252C%25252520readBlog%252529%2525250A%25252509router.POST%252528%25252522%2525252Fupdate%2525252F%2525253Aid%25252522%2525252C%25252520updateBlog%252529%2525250A%25252509router.GET%252528%25252522%2525252Fdelete%2525252F%2525253Aid%25252522%2525252C%25252520deleteBlog%252529%2525250A%2525257D%2525250A%2525250A%2525252F%2525252F%25252520By%25252520default%25252520it%25252520serves%25252520on%25252520%2525253A8080%2525250Ar.Run%252528%252529&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b2c90de3c03c4d37818fb771c6a2829/href">https://medium.com/media/3b2c90de3c03c4d37818fb771c6a2829/href</a></iframe><p>Before moving forward, let’s talk about above code a little bit.</p><p>We use r:=gin.Default() to start the default router. Next we defined a group with a variable name router . This initiates a group of routes with a URL prefix /blogs . In this group we’ve four routes to handle CRUD requests.</p><ul><li>‘/create’ Route : This route handles a POST Request from user and maps to the postBlog() function. Later we’ll use this handler to create a new record in blogs table in SQLite Database.</li><li>‘/’ Route : This route handles a GET Request and maps to the readBlog() . It returns all records from blogs table in JSON Format.</li><li>‘/update’ Route : This route handles a POST Request and maps to the updateBlog() function which will update a record with specific a id.</li><li>‘/delete’ Route : This route handles a GET Request and maps to the deleteBlog() function which will delete a record with specific a id.</li></ul><p>Hope you got the basic idea of GIN Framework routes. Now, we’ll define all handler functions.</p><h3>Handler Functions</h3><p>For now We’ll just define handlers without any real data handling. Just copy the following code and paste it after main() function</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528251%252C251%252C251%252C1%2529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunc%252520postBlog%2528c%252520%252Agin.Context%2529%252520%25257B%25250A%252509c.JSON%2528200%25252C%252520gin.H%25257B%252522message%252522%25253A%252520%252522A%252520new%252520Record%252520Created%2521%252522%25257D%2529%25250A%25257D%25250A%25250Afunc%252520readBlog%2528c%252520%252Agin.Context%2529%252520%25257B%25250A%252509c.JSON%2528200%25252C%252520gin.H%25257B%252522message%252522%25253A%252520%252522All%252520Records%252522%25257D%2529%25250A%25257D%25250A%25250Afunc%252520updateBlog%2528c%252520%252Agin.Context%2529%252520%25257B%25250A%252509c.JSON%2528200%25252C%252520gin.H%25257B%252522message%252522%25253A%252520%252522Record%252520Updated%2521%252522%25257D%2529%25250A%25257D%25250Afunc%252520deleteBlog%2528c%252520%252Agin.Context%2529%252520%25257B%25250A%252509c.JSON%2528200%25252C%252520gin.H%25257B%252522message%252522%25253A%252520%252522Record%252520Deleted%2521%252522%25257D%2529%25250A%25257D%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528251%25252C251%25252C251%25252C1%252529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%25252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunc%25252520postBlog%252528c%25252520%25252Agin.Context%252529%25252520%2525257B%2525250A%25252509c.JSON%252528200%2525252C%25252520gin.H%2525257B%25252522message%25252522%2525253A%25252520%25252522A%25252520new%25252520Record%25252520Created%252521%25252522%2525257D%252529%2525250A%2525257D%2525250A%2525250Afunc%25252520readBlog%252528c%25252520%25252Agin.Context%252529%25252520%2525257B%2525250A%25252509c.JSON%252528200%2525252C%25252520gin.H%2525257B%25252522message%25252522%2525253A%25252520%25252522All%25252520Records%25252522%2525257D%252529%2525250A%2525257D%2525250A%2525250Afunc%25252520updateBlog%252528c%25252520%25252Agin.Context%252529%25252520%2525257B%2525250A%25252509c.JSON%252528200%2525252C%25252520gin.H%2525257B%25252522message%25252522%2525253A%25252520%25252522Record%25252520Updated%252521%25252522%2525257D%252529%2525250A%2525257D%2525250Afunc%25252520deleteBlog%252528c%25252520%25252Agin.Context%252529%25252520%2525257B%2525250A%25252509c.JSON%252528200%2525252C%25252520gin.H%2525257B%25252522message%25252522%2525253A%25252520%25252522Record%25252520Deleted%252521%25252522%2525257D%252529%2525250A%2525257D%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/73d6d74288847cde862e0a6e444fab14/href">https://medium.com/media/73d6d74288847cde862e0a6e444fab14/href</a></iframe><p>Functions are pretty self explanatory. We’re just handing every request and returning a JSON response with status 200 [1].</p><p>Now run the build command in Powershell to compile project into executable code and run it.</p><pre>go build</pre><pre>.\blog.exe</pre><p>This will start the server on default PORT 8080. Now, we’ll taste our API Routes with Postman. To make things simple I already Created API Testing Project for you. You can go <a href="https://raw.githubusercontent.com/satadeep3927/go-api-demo/main/Postman/Go-Demo.postman_collection.json">here</a> and download file by pressing ctrl+s . Now Launch Postman and Import previously downloaded JSON file. You’ll see imported project in left side-bar. click on the project and send every requests individually. Successful request returns a data with Status code 200.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8s-Hg4ghBem6bMSaOLp0AA.png" /></figure><p>We completed router setup and now we’ll focus on the most interesting part of this Lesson. We’ll create SQLite Database and make things alive.</p><h3>Creating Database</h3><p>As I said Earlier that we’ll use a online SQLite Client to create and manage our Database. Visit <a href="https://sqliteonline.com/">sqliteonline.com</a> to create our database. Run following command on their integrated shell.</p><pre><strong>DROP</strong> <strong>TABLE</strong> demo</pre><p>This command will delete default table from database. We will follow very simple Database Schema.</p><ul><li>id : <strong>INTEGER PRIMARY KEY AUTO INCREMENT</strong></li><li>author : <strong>TEXT</strong></li><li>title : <strong>TEXT</strong></li><li>content : <strong>TEXT</strong></li><li>image : <strong>TEXT</strong></li><li>created_at : <strong>DATETIME</strong></li></ul><p>We’ll create blogs table by running following command.</p><pre><strong>CREATE TABLE</strong> blogs ( id <strong>INTEGER PRIMARY</strong> <strong>KEY AUTOINCREMENT</strong>, author <strong>TEXT</strong>, title <strong>TEXT</strong>, content <strong>TEXT</strong>,image <strong>TEXT,</strong> created_at <strong>DATETIME DEFAULT CURRENT_DATE</strong> )</pre><p>Let our hands get together. We just created our SQLite Database!!!</p><p>Now download it from File &gt; Save DB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*chYOSk-vEgVSzOIRiAkotQ.png" /></figure><p><strong>You need to move this database file from default download location to your project directory.</strong></p><p>We’ll create a new directory inside our project folder named models. Let’s create a new file named blogs.go inside models folder. This file will be used to interact with database. Add below code snippet to import required libraries.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528251%252C251%252C251%252C1%2529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dpackage%252520models%25250A%25250Aimport%252520%2528%25250A%252509%252522database%25252Fsql%252522%25250A%252509_%252520%252522github.com%25252Fmattn%25252Fgo-sqlite3%252522%25250A%2529&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528251%25252C251%25252C251%25252C1%252529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%25252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dpackage%25252520models%2525250A%2525250Aimport%25252520%252528%2525250A%25252509%25252522database%2525252Fsql%25252522%2525250A%25252509_%25252520%25252522github.com%2525252Fmattn%2525252Fgo-sqlite3%25252522%2525250A%252529&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/be7f6bd1c2ef8ea76369f77edbf0a2bc/href">https://medium.com/media/be7f6bd1c2ef8ea76369f77edbf0a2bc/href</a></iframe><p>Now we’ll declare a global variable before our main() function.</p><pre>var DB *sql.DB</pre><p>Now we’ll write a function to make a stable connection with SQLite Database Engine.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528251%252C251%252C251%252C1%2529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunc%252520ConnectDatabase%2528%2529%252520error%252520%25257B%25250A%252509db%25252C%252520err%252520%25253A%25253D%252520sql.Open%2528%252522sqlite3%252522%25252C%252520%252522.%25252Fsqlite.db%252522%2529%25250A%252509if%252520err%252520%2521%25253D%252520nil%252520%25257B%25250A%252509%252509return%252520err%25250A%252509%25257D%25250A%25250A%252509DB%252520%25253D%252520db%25250A%252509return%252520nil%25250A%25257D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528251%25252C251%25252C251%25252C1%252529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%25252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunc%25252520ConnectDatabase%252528%252529%25252520error%25252520%2525257B%2525250A%25252509db%2525252C%25252520err%25252520%2525253A%2525253D%25252520sql.Open%252528%25252522sqlite3%25252522%2525252C%25252520%25252522.%2525252Fsqlite.db%25252522%252529%2525250A%25252509if%25252520err%25252520%252521%2525253D%25252520nil%25252520%2525257B%2525250A%25252509%25252509return%25252520err%2525250A%25252509%2525257D%2525250A%2525250A%25252509DB%25252520%2525253D%25252520db%2525250A%25252509return%25252520nil%2525250A%2525257D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4efebe99dcddb53b43f1c4a7c2ce3ae9/href">https://medium.com/media/4efebe99dcddb53b43f1c4a7c2ce3ae9/href</a></iframe><p>The Open method comes from the database/sql package, however, there are no database drivers included in the standard library, so you must import one. We imported the go-sqlite3 library for our driver.</p><h3>Creating Model</h3><p>We created routes , Handlers and Database connection. Now we’ll create a very simple <strong>MODEL.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528251%252C251%252C251%252C1%2529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dtype%252520Blog%252520struct%252520%25257B%25250A%252509Id%252520%252520%252520%252520%252520%252520%252520%252520%252520int%252520%252520%252520%252520%252560json%25253A%252522id%252522%252560%25250A%252509Author%252520%252520%252520%252520%252520string%252520%252560json%25253A%252522author%252522%252560%25250A%252509Title%252520%252520%252520%252520%252520%252520string%252520%252560json%25253A%252522title%252522%252560%25250A%252509Content%252520%252520%252520%252520string%252520%252560json%25253A%252522content%252522%252560%25250A%252509Image%252520%252520%252520%252520%252520%252520string%252520%252560json%25253A%252522image%252522%252560%25250A%252509Created_at%252520string%252520%252560json%25253A%252522createdAt%252522%252560%25250A%25257D&amp;display_name=Carbon&amp;url=http%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528251%25252C251%25252C251%25252C1%252529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%25252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dtype%25252520Blog%25252520struct%25252520%2525257B%2525250A%25252509Id%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520int%25252520%25252520%25252520%25252520%25252560json%2525253A%25252522id%25252522%25252560%2525250A%25252509Author%25252520%25252520%25252520%25252520%25252520string%25252520%25252560json%2525253A%25252522author%25252522%25252560%2525250A%25252509Title%25252520%25252520%25252520%25252520%25252520%25252520string%25252520%25252560json%2525253A%25252522title%25252522%25252560%2525250A%25252509Content%25252520%25252520%25252520%25252520string%25252520%25252560json%2525253A%25252522content%25252522%25252560%2525250A%25252509Image%25252520%25252520%25252520%25252520%25252520%25252520string%25252520%25252560json%2525253A%25252522image%25252522%25252560%2525250A%25252509Created_at%25252520string%25252520%25252560json%2525253A%25252522createdAt%25252522%25252560%2525250A%2525257D&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b8408339d29748baef5b90316b510f1/href">https://medium.com/media/6b8408339d29748baef5b90316b510f1/href</a></iframe><p>We’ll use our Blog Model for transitioning data between Database and Web.</p><p>[1] Status Code 200 indicates a successful request and response.</p><h4>Retrieving all Records from the blogs Table (GetBlogs)</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528251%252C251%252C251%252C1%2529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunc%252520GetBlogs%2528%2529%252520%2528%25255B%25255DBlog%25252C%252520error%2529%252520%25257B%25250A%25250A%252509rows%25252C%252520err%252520%25253A%25253D%252520DB.Query%2528%252522SELECT%252520%252A%252520FROM%252520blogs%252522%2529%25250A%25250A%252509if%252520err%252520%2521%25253D%252520nil%252520%25257B%25250A%252509%252509return%252520nil%25252C%252520err%25250A%252509%25257D%25250A%25250A%252509defer%252520rows.Close%2528%2529%25250A%25250A%252509blogs%252520%25253A%25253D%252520make%2528%25255B%25255DBlog%25252C%2525200%2529%25250A%25250A%252509for%252520rows.Next%2528%2529%252520%25257B%25250A%252509%252509singleBlog%252520%25253A%25253D%252520Blog%25257B%25257D%25250A%252509%252509err%252520%25253D%252520rows.Scan%2528%252526singleBlog.Id%25252C%252520%252526singleBlog.Author%25252C%252520%252526singleBlog.Title%25252C%252520%252526singleBlog.Content%25252C%252520%252526singleBlog.Image%25252C%252520%252526singleBlog.Created_at%2529%25250A%25250A%252509%252509if%252520err%252520%2521%25253D%252520nil%252520%25257B%25250A%252509%252509%252509return%252520nil%25252C%252520err%25250A%252509%252509%25257D%25250A%25250A%252509%252509blogs%252520%25253D%252520append%2528blogs%25252C%252520singleBlog%2529%25250A%252509%25257D%25250A%25250A%252509err%252520%25253D%252520rows.Err%2528%2529%25250A%25250A%252509if%252520err%252520%2521%25253D%252520nil%252520%25257B%25250A%252509%252509return%252520nil%25252C%252520err%25250A%252509%25257D%25250A%25250A%252509return%252520blogs%25252C%252520nil%25250A%25257D%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528251%25252C251%25252C251%25252C1%252529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%25252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunc%25252520GetBlogs%252528%252529%25252520%252528%2525255B%2525255DBlog%2525252C%25252520error%252529%25252520%2525257B%2525250A%2525250A%25252509rows%2525252C%25252520err%25252520%2525253A%2525253D%25252520DB.Query%252528%25252522SELECT%25252520%25252A%25252520FROM%25252520blogs%25252522%252529%2525250A%2525250A%25252509if%25252520err%25252520%252521%2525253D%25252520nil%25252520%2525257B%2525250A%25252509%25252509return%25252520nil%2525252C%25252520err%2525250A%25252509%2525257D%2525250A%2525250A%25252509defer%25252520rows.Close%252528%252529%2525250A%2525250A%25252509blogs%25252520%2525253A%2525253D%25252520make%252528%2525255B%2525255DBlog%2525252C%252525200%252529%2525250A%2525250A%25252509for%25252520rows.Next%252528%252529%25252520%2525257B%2525250A%25252509%25252509singleBlog%25252520%2525253A%2525253D%25252520Blog%2525257B%2525257D%2525250A%25252509%25252509err%25252520%2525253D%25252520rows.Scan%252528%25252526singleBlog.Id%2525252C%25252520%25252526singleBlog.Author%2525252C%25252520%25252526singleBlog.Title%2525252C%25252520%25252526singleBlog.Content%2525252C%25252520%25252526singleBlog.Image%2525252C%25252520%25252526singleBlog.Created_at%252529%2525250A%2525250A%25252509%25252509if%25252520err%25252520%252521%2525253D%25252520nil%25252520%2525257B%2525250A%25252509%25252509%25252509return%25252520nil%2525252C%25252520err%2525250A%25252509%25252509%2525257D%2525250A%2525250A%25252509%25252509blogs%25252520%2525253D%25252520append%252528blogs%2525252C%25252520singleBlog%252529%2525250A%25252509%2525257D%2525250A%2525250A%25252509err%25252520%2525253D%25252520rows.Err%252528%252529%2525250A%2525250A%25252509if%25252520err%25252520%252521%2525253D%25252520nil%25252520%2525257B%2525250A%25252509%25252509return%25252520nil%2525252C%25252520err%2525250A%25252509%2525257D%2525250A%2525250A%25252509return%25252520blogs%2525252C%25252520nil%2525250A%2525257D%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/524368a00873b073353dce11f1c65d1d/href">https://medium.com/media/524368a00873b073353dce11f1c65d1d/href</a></iframe><p>Now, let’s discuss about the code.</p><p>We declare the function GetBlogs() :</p><pre>func GetBlogs() ([]Blog, error){</pre><p>We’re initializing function without any arguments and returning Slice Blog and an error. So anytime something fails within this function, we’ll return nil for the slice and the error. We’ll then read it later.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528251%252C251%252C251%252C1%2529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Drows%25252C%252520err%252520%25253A%25253D%252520DB.Query%2528%252522SELECT%252520%252A%252520FROM%252520blogs%252522%2529%25250A%25250Aif%252520err%252520%2521%25253D%252520nil%252520%25257B%25250A%252509return%252520nil%25252C%252520err%25250A%25257D%25250A%25250Adefer%252520rows.Close%2528%2529%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528251%25252C251%25252C251%25252C1%252529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%25252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Drows%2525252C%25252520err%25252520%2525253A%2525253D%25252520DB.Query%252528%25252522SELECT%25252520%25252A%25252520FROM%25252520blogs%25252522%252529%2525250A%2525250Aif%25252520err%25252520%252521%2525253D%25252520nil%25252520%2525257B%2525250A%25252509return%25252520nil%2525252C%25252520err%2525250A%2525257D%2525250A%2525250Adefer%25252520rows.Close%252528%252529%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/033ec59e5a8d839d0171c930ed8ef109/href">https://medium.com/media/033ec59e5a8d839d0171c930ed8ef109/href</a></iframe><p>Here we’re running a simple Database query to select every row from blogs Table.</p><p>We check for an error on the query and defer the Close() method for the rows to ensure it doesn’t stay open after we’re done.</p><p>Now, we are going to create a new slice blogs :</p><pre>blogs := make([]Blog, 0)</pre><p>Then we’ll iterate through the results:</p><pre>for rows.Next() {</pre><p>Now, we’ll create a Blog Struct :</p><pre>singleBlog := Blog{}</pre><p>Then we’ll use rows.Scan to scan the values returned in the row and bind them to the singleBlog object we just created.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528251%252C251%252C251%252C1%2529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Derr%252520%25253D%252520rows.Scan%2528%252526singleBlog.Id%25252C%252520%252526singleBlog.Author%25252C%252520%252526singleBlog.Title%25252C%252520%252526singleBlog.Content%25252C%252520%252526singleBlog.Image%25252C%252520%252526singleBlog.Created_at%2529%25250A%25250Aif%252520err%252520%2521%25253D%252520nil%252520%25257B%25250A%252509return%252520nil%25252C%252520err%25250A%25257D%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528251%25252C251%25252C251%25252C1%252529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%25252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Derr%25252520%2525253D%25252520rows.Scan%252528%25252526singleBlog.Id%2525252C%25252520%25252526singleBlog.Author%2525252C%25252520%25252526singleBlog.Title%2525252C%25252520%25252526singleBlog.Content%2525252C%25252520%25252526singleBlog.Image%2525252C%25252520%25252526singleBlog.Created_at%252529%2525250A%2525250Aif%25252520err%25252520%252521%2525253D%25252520nil%25252520%2525257B%2525250A%25252509return%25252520nil%2525252C%25252520err%2525250A%2525257D%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dde75f0706e994164fae0f8603b9a8c/href">https://medium.com/media/4dde75f0706e994164fae0f8603b9a8c/href</a></iframe><p>We do another quick check for a Scan error.</p><p>Now, we’ll append our new Object into the blogs Slice.</p><pre>blogs = append(blogs, singleBlog)</pre><p>I thinks it’s enough explanation for understanding the core concept. Now, we’ll go to the our main.go file and a line to import function our Blog Model.</p><pre>&quot;example.com/demo/models&quot;</pre><p>We’ll define a very simple function to handle errors.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528251%252C251%252C251%252C1%2529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunc%252520checkErr%2528err%252520error%2529%252520%25257B%25250A%252509if%252520err%252520%2521%25253D%252520nil%252520%25257B%25250A%252509%252509log.Fatal%2528err%2529%25250A%252509%25257D%25250A%25257D%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528251%25252C251%25252C251%25252C1%252529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%25252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunc%25252520checkErr%252528err%25252520error%252529%25252520%2525257B%2525250A%25252509if%25252520err%25252520%252521%2525253D%25252520nil%25252520%2525257B%2525250A%25252509%25252509log.Fatal%252528err%252529%2525250A%25252509%2525257D%2525250A%2525257D%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3394d283f3f4f56541f785ef51123a7d/href">https://medium.com/media/3394d283f3f4f56541f785ef51123a7d/href</a></iframe><p>To initiate the connection with SQLite database we have to call ConnectDatabase() function from our main() function. So, replace our previous function with following new code.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528251%252C251%252C251%252C1%2529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunc%252520main%2528%2529%252520%25257B%25250A%252509err%252520%25253A%25253D%252520models.ConnectDatabase%2528%2529%25250A%252509checkErr%2528err%2529%25250A%25250A%252509r%252520%25253A%25253D%252520gin.Default%2528%2529%25250A%25250A%252509%25252F%25252F%252520API%252520Blogs%25250A%252509router%252520%25253A%25253D%252520r.Group%2528%252522%25252Fblogs%252522%2529%25250A%252509%25257B%25250A%252509%252509router.POST%2528%252522%25252Fcreate%252522%25252C%252520postBlog%2529%25250A%252509%252509router.GET%2528%252522%25252F%252522%25252C%252520readBlog%2529%25250A%252509%252509router.POST%2528%252522%25252Fupdate%25252F%25253Aid%252522%25252C%252520updateBlog%2529%25250A%252509%252509router.GET%2528%252522%25252Fdelete%25252F%25253Aid%252522%25252C%252520deleteBlog%2529%25250A%252509%25257D%25250A%25250A%252509%25252F%25252F%252520By%252520default%252520it%252520serves%252520on%252520%25253A8080%25250A%252509r.Run%2528%2529%25250A%25257D%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528251%25252C251%25252C251%25252C1%252529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%25252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunc%25252520main%252528%252529%25252520%2525257B%2525250A%25252509err%25252520%2525253A%2525253D%25252520models.ConnectDatabase%252528%252529%2525250A%25252509checkErr%252528err%252529%2525250A%2525250A%25252509r%25252520%2525253A%2525253D%25252520gin.Default%252528%252529%2525250A%2525250A%25252509%2525252F%2525252F%25252520API%25252520Blogs%2525250A%25252509router%25252520%2525253A%2525253D%25252520r.Group%252528%25252522%2525252Fblogs%25252522%252529%2525250A%25252509%2525257B%2525250A%25252509%25252509router.POST%252528%25252522%2525252Fcreate%25252522%2525252C%25252520postBlog%252529%2525250A%25252509%25252509router.GET%252528%25252522%2525252F%25252522%2525252C%25252520readBlog%252529%2525250A%25252509%25252509router.POST%252528%25252522%2525252Fupdate%2525252F%2525253Aid%25252522%2525252C%25252520updateBlog%252529%2525250A%25252509%25252509router.GET%252528%25252522%2525252Fdelete%2525252F%2525253Aid%25252522%2525252C%25252520deleteBlog%252529%2525250A%25252509%2525257D%2525250A%2525250A%25252509%2525252F%2525252F%25252520By%25252520default%25252520it%25252520serves%25252520on%25252520%2525253A8080%2525250A%25252509r.Run%252528%252529%2525250A%2525257D%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0f2c46eea480fdb50d30189817df1e6/href">https://medium.com/media/b0f2c46eea480fdb50d30189817df1e6/href</a></iframe><p>We established connection with Database now, we’ll try to retrieve records from database. Let’s update readBlog() Handler function with new code.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528251%252C251%252C251%252C1%2529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunc%252520readBlog%2528c%252520%252Agin.Context%2529%252520%25257B%25250A%252509blogs%25252C%252520err%252520%25253A%25253D%252520models.GetBlogs%2528%2529%25250A%252509checkErr%2528err%2529%25250A%25250A%252509if%252520blogs%252520%25253D%25253D%252520nil%252520%25257B%25250A%252509%252509c.JSON%2528404%25252C%252520gin.H%25257B%252522error%252522%25253A%252520%252522No%252520Records%252520Found%252522%25257D%2529%25250A%252509%252509return%25250A%252509%25257D%252520else%252520%25257B%25250A%252509%252509c.JSON%2528200%25252C%252520gin.H%25257B%252522data%252522%25253A%252520blogs%25257D%2529%25250A%252509%25257D%25250A%25257D%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528251%25252C251%25252C251%25252C1%252529%26t%3Dcobalt%26wt%3Dsharp%26l%3Dtext%25252Fx-go%26width%3D757.75%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D0px%26ph%3D0px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D15px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunc%25252520readBlog%252528c%25252520%25252Agin.Context%252529%25252520%2525257B%2525250A%25252509blogs%2525252C%25252520err%25252520%2525253A%2525253D%25252520models.GetBlogs%252528%252529%2525250A%25252509checkErr%252528err%252529%2525250A%2525250A%25252509if%25252520blogs%25252520%2525253D%2525253D%25252520nil%25252520%2525257B%2525250A%25252509%25252509c.JSON%252528404%2525252C%25252520gin.H%2525257B%25252522error%25252522%2525253A%25252520%25252522No%25252520Records%25252520Found%25252522%2525257D%252529%2525250A%25252509%25252509return%2525250A%25252509%2525257D%25252520else%25252520%2525257B%2525250A%25252509%25252509c.JSON%252528200%2525252C%25252520gin.H%2525257B%25252522data%25252522%2525253A%25252520blogs%2525257D%252529%2525250A%25252509%2525257D%2525250A%2525257D%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/988672bdcc4d591baca59686a2cb83c9/href">https://medium.com/media/988672bdcc4d591baca59686a2cb83c9/href</a></iframe><p>Before moving further, we should taste our code. Run build command to compile project into executable file and run executable file from command prompt. Test Create Route from your Postman software. If it’s returning response code 200 then application is working properly.</p><p>Let’s walk through our project</p><ul><li>We configured routes and corresponding Handler functions.</li><li>We created Model to transmit data between database and web.</li><li>We defined GetBlogs() function to retrieve all records from database.</li></ul><p>In the next Part of this Article we’ll try to create functions to handle other request like CREATE, UPDATE and DELETE.</p><figure><a href="https://faun.to/bP1m5"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCiLLad3dvZLwBa-B5cAVQ.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97c29ed2f282" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/building-a-rest-api-with-go-and-sqlite-part-1-97c29ed2f282">BUILDING A REST API WITH GO AND SQLITE(PART 1)</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Expertise the JSON file handling in Python using practical examples(Part-1)]]></title>
            <link>https://faun.pub/expertise-the-json-file-handling-in-python-using-practical-examples-part-1-d5c104222fd3?source=rss-f658f9a6a27a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5c104222fd3</guid>
            <category><![CDATA[beginner-coding]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[projects]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Satadeep Dasgupta]]></dc:creator>
            <pubDate>Wed, 23 Jun 2021 18:29:43 GMT</pubDate>
            <atom:updated>2021-06-25T20:02:13.257Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pg7YxyNXkZQEWnLMJ0EpgA.jpeg" /><figcaption>Fig1: Photo by <a href="https://realpython.com/python-json/#author">Lucas Lofaro</a> from <a href="https://realpython.com/python-json/">Real Python</a></figcaption></figure><h4>A brief and beginner friendly introduction to JavaScript Object Notation for python learner with two mini-projects</h4><p><strong>JSON</strong> or <strong>JavaScript Object Notation</strong>, is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs like <strong>Python</strong> <strong>Dictionary</strong> and <strong>arrays</strong> (or <strong>list</strong> in python). It is a very common data format, with a diverse range of applications, one example being web applications that communicate with a server.</p><p><strong>JSON</strong> is a language-independent data format. It was derived from <strong>JavaScript</strong>, but many modern programming languages include code to generate and parse<strong> JSON</strong>-format data. <strong>JSON</strong> filenames use the extension .json. It’s <strong>Data Format </strong>makes it so powerful and readable for a programmer. That’s why I prefer <strong>JSON </strong>over <strong>CSV.</strong></p><h3>Syntactical Discussion</h3><p>It’s really easy to understand the syntax of <strong>JSON </strong>file. It’s structure looks like the combination of python <strong>list</strong> and <strong>dictionary. </strong>A example is here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32ec1de9b80687a2d730a677dfd56e78/href">https://medium.com/media/32ec1de9b80687a2d730a677dfd56e78/href</a></iframe><p>We’ll use its <strong>keys</strong> and <strong>Positional Index </strong>to get the desired value but before that, we have to convert <strong>JSON </strong>String to the Python readable format with <strong>json.loads()</strong> function. Let’s go through a example.</p><p>First we’ll <strong>import</strong> default <strong>json </strong>library. then we’ll define a simple JSON string and try to use it’s values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b0156d7b22ced4f7447be33c328877f/href">https://medium.com/media/9b0156d7b22ced4f7447be33c328877f/href</a></iframe><p>We have a simple <strong>JSON </strong>string and then <strong>json.loads()</strong> function converts it to the python readable dictionary. Now, we can use its values via its keys as we do with native dictionaries.</p><h3>Data types</h3><p><strong>JSON </strong>supports basic data type like other programming languages:</p><ul><li><strong>Number</strong>: a signed decimal number that may contain a fractional part and may use exponential E notation. The format makes no distinction between integer and floating-point.</li><li><strong>String</strong>: a sequence of zero or more Unicode characters. Strings are delimited with double-quotation marks and support a backslash escaping syntax.</li><li><strong>Boolean</strong>: either of the values true or false</li><li><strong>Array</strong>: an ordered list of zero or more elements, each of which may be of any type. Arrays use square bracket notation with comma-separated elements like <strong>Python list</strong>.</li><li><strong>Object</strong>: a collection of name–value pairs where the names (also called keys) are strings. Objects are intended to represent associative arrays, where each key is unique within an object. Objects are delimited with curly brackets and use commas to separate each pair, while within each pair the colon ‘:’ character separates the key or name from its value.</li><li><strong>Null </strong>: an empty value, using the word null</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rU3U0EGo6vbtu8tDSU_w1A.png" /><figcaption>Fig2: Image from Json.org</figcaption></figure><p><strong>Whitespace</strong> is allowed and ignored around or between syntactic elements (values and punctuation, but not within a string value). Four specific characters are considered whitespace for this purpose: space, horizontal tab, line feed, and carriage return. In particular, the byte order mark must not be generated by a conforming implementation (though it may be accepted when parsing JSON). JSON does not provide syntax for comments.</p><h3>What can we do with JSON?</h3><p>There are some popular usage of JSON</p><ul><li>JSON format is used for serializing and transmitting structured data over network connection.</li><li>It is primarily used to transmit data between a server and web applications.</li><li>Web services and APIs use JSON format to provide public data.</li><li>JSON file can be used to store humongous structured data in machine and server</li></ul><p>Let’s see how we can store and retrieve data with <strong>JSON…</strong></p><p>Create two files in your project directory, <strong>test.py</strong> and <strong>store.json</strong>. In <strong>store.json</strong> file copy and paste the JSON data from snippet-1. Now, open test.py and import json library via import statement. We’ll read JSON file with open function. Let’s write it all together.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6b879bb45e75916533e26bc967605e1/href">https://medium.com/media/a6b879bb45e75916533e26bc967605e1/href</a></iframe><p>It will print the JSON data in your terminal. Now, we’ll create a function to rewrite existing data in JSON file. In this scenario will use <strong>open()</strong> function with <strong>write(w)</strong> mode and <strong>write()</strong> function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1700c0a04164ba7a1ef7c74b4751c9a4/href">https://medium.com/media/1700c0a04164ba7a1ef7c74b4751c9a4/href</a></iframe><p>So, we learned to open and print JSON files and rewrite their data. NOW, we’ll do some modifications to our existing JSON data to understand the procedure more accurately.</p><h3>Deleting a Key from JSON data</h3><p>In <strong>snippet-3 </strong>we converted JSON data into Python readable object. We’ll use the default <strong>pop() </strong>function to remove a key from a converted object and then we’ll pass the value to the predefined <strong>modifystore()</strong> function to rewrite the file. Let’s write it all together.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04cf3f754b21733db4f25561890159e2/href">https://medium.com/media/04cf3f754b21733db4f25561890159e2/href</a></iframe><p>Here, <strong>json.dumps() </strong>converts python object to the <strong>JSON </strong>String. If the code runs without any error, you’ll see that “<strong>firstName</strong>” key is now removed from <strong>test.json </strong>file.</p><h3>Modifying existing JSON Data</h3><p>In previous example, we tried to remove a key from JSON file. Now, we’ll try to modify existing data. Let’s assume that we want to change the office Telephone number of the JSON file(<strong>snippet-1 and line-15</strong>). As a previous example, we’ll convert JSON string into Python object then we’ll use <strong>keys </strong>to modify data. let’s write it</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f01327ca9aecd3eccffa1d8174e51e89/href">https://medium.com/media/f01327ca9aecd3eccffa1d8174e51e89/href</a></iframe><p>Run the code and <strong>boom!!! </strong>the office number changed into your specified number.</p><p>We learnt to Modify JSON file. it’s pretty enough knowledge to develop something cool. So, let’s discuss our first mini-project…</p><h3>Mini Project using JSON and Python</h3><p>Learning without implementing is just waste of time. We’ve learned about storing and retrieving JSON and we’ll try to implement our existing knowledge in this mini project. After a long time, I decided to build a <strong>CLI(Command line interface) tool to manage contacts </strong>and that is one of the coolest things you can build as a beginner. User can add, delete and modify existing data. The flow of application will look like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*7dmsA7e8n5iOTyg_ZZxujA.png" /><figcaption>Fig3: Flow of our CLI based Contact Manager</figcaption></figure><p>It’s looks complicated, right? but it’s pretty simple. Don’t think about it to much. We’ll understand it in few stapes. At first, we’ll write a <strong>menu-driven</strong> program to take user input and save it to the store as a new object.</p><ul><li><strong>Step 1: writing a menu-driven program to take user input and save it to the store as a new object.</strong></li></ul><p>We’ll create two files in our project directory, <strong>contact.py</strong> and <strong>data.json. </strong>In our JSON file we’ll write empty square braces(like, []) and that’s it. Now, let’s jump to the contact.py. we’ll import json library like previous examples. we’ll open JSON file and convert it’s data to the Python readable object. we defined a <strong>modifystore() </strong>function to rewrite JSON file. It can be reused here. We’ll use the <strong>input() </strong>function to take user input and serve things according to the input. Let’s write it together.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7558bd8c900961a4b0808ec5a76282b9/href">https://medium.com/media/7558bd8c900961a4b0808ec5a76282b9/href</a></iframe><p>in <strong>snippet-7 </strong>we used color code to wrap text in <strong>print()</strong> function. It will print color text in terminal. Now run it. You’ll see that program prints list of options in terminal and takes a user input. If user input is 1 then the program will create a piece of new contact information by taking the name, phone number, email. Let’s see practically</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c61d0aefe89308cd6bdd50719037f544/href">https://medium.com/media/c61d0aefe89308cd6bdd50719037f544/href</a></iframe><p>In this is the example we took user inputs and checking if the name field is empty, and storing it in the JSON file. Run it and select option, feel the requirement and that should work perfectly. Now, check JSON file. You’ll see that a new object is added with your provided information. <strong>Cool!!</strong></p><ul><li><strong>Step-2: Searching for a name in JSON file and tying to modify or delete it</strong></li></ul><p>If the user selects option 2 then, we’ll ask the name for searching then we’ll use a <strong>for loop</strong> to check the name <strong>key</strong> of every object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/235b4f153c24a0fba32f7e0c1fd00bf4/href">https://medium.com/media/235b4f153c24a0fba32f7e0c1fd00bf4/href</a></iframe><p>We’re checking every value of name key and showing them to user. Now, we’ll give user options to delete or modify the object. If user want to modify existing information, we’ll use his input to change existing values with new one, like that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7f1e05ba8b7b745d6d4782d89a66344/href">https://medium.com/media/a7f1e05ba8b7b745d6d4782d89a66344/href</a></iframe><p>We’re replacing old values of store object with <strong>non empty</strong> new values using a for loop. Code should work perfectly.</p><p>Deleting a Object is much more simple. We’ll use <strong>remove() </strong>function to remove the object from store. Like that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9db9cc337cea48921f8c5be4ad1ae1b6/href">https://medium.com/media/9db9cc337cea48921f8c5be4ad1ae1b6/href</a></iframe><p>No complexity at all. We’re just confirming the decision and if user input is <strong>“y” </strong>then the information will be deleted.</p><p>Third and Final step is simplest one. We’ll show every information using a for loop</p><ul><li><strong>Step-3: Showing all available information to the user</strong></li></ul><p>We’ll use a simple <strong>Traversing </strong>show every available result to the user. Let’s do it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ed4e59e36bb98b0dcbf84b685669b53/href">https://medium.com/media/9ed4e59e36bb98b0dcbf84b685669b53/href</a></iframe><p>Run it and use it few times. I think code will run perfectly.</p><h3>Conclusion</h3><p>We tried to discuss about JSON elaborately, analyzed it’s syntax, tried to modified too. At the end we built a <strong>CLI tool for Managing Contacts. </strong>That’s one of the many uses of <strong>JSON </strong>Data. In the next part, we’ll do one more interesting project and discuss one more popular usage of <strong>JSON. </strong>Don’t hesitate to response with your problems and don’t forget to clap</p><p><strong>Happy Coding!!!</strong></p><figure><a href="https://faun.to/i9Pt9"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_MOgMTr_f1N4qHN_R7KVA.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5c104222fd3" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/expertise-the-json-file-handling-in-python-using-practical-examples-part-1-d5c104222fd3">Expertise the JSON file handling in Python using practical examples(Part-1)</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[May be Puppeteer is the tool you want for Web Automation]]></title>
            <link>https://satadeepdasgupta.medium.com/may-be-puppeteer-is-the-tool-you-want-for-web-automation-1cd2a1e3fcdf?source=rss-f658f9a6a27a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cd2a1e3fcdf</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[web-automation]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[puppeteer]]></category>
            <dc:creator><![CDATA[Satadeep Dasgupta]]></dc:creator>
            <pubDate>Fri, 18 Jun 2021 19:37:58 GMT</pubDate>
            <atom:updated>2021-06-20T07:33:23.388Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*W_tmHDYCrfUDxZGHB9F_Tg.png" /></figure><h3>Introduction</h3><p><strong>Puppeteer</strong> is a Node library created by <strong>Chrome</strong> development team which provides a high-level API to control <strong>headless Chrome</strong> or<strong> Chromium</strong> over the<strong> Dev-Tool Protocol</strong>. It can also be configured to use full (non-headless) <strong>Chrome</strong> or <strong>Chromium</strong>. Basically, It can perform any automated task for you.</p><h3>What can be done with puppeteer?</h3><p>Most things that you do manually in your browser can be done easily and efficiently using <strong>Puppeteer</strong>! Let’s look at some of most useful and popular task.</p><ol><li>Crawling and Scraping Single page Web Applications along with Pre-rendered Web Applications.</li><li>Generate PDFs and Images of any website.</li><li>Automate login, form submission, User Interface testing, etc.</li><li>You can create a Automated testing Environment and run tests directly in the latest version of <strong>Chromium.</strong></li></ol><h3>Getting Started</h3><p>Let’s start our project by initiating a new node project by using this sample command.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2d826ad13f008f26d44d3552a3fe7eb/href">https://medium.com/media/c2d826ad13f008f26d44d3552a3fe7eb/href</a></iframe><h3>Installation</h3><p>Installing <strong>Puppeteer </strong>is pretty simple task. Thanks to <strong>NPM </strong>and<strong> Yarn. </strong>You need to use this simple command to install <strong>puppeteer.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/241547b056316ee2f237803c0147dbca/href">https://medium.com/media/241547b056316ee2f237803c0147dbca/href</a></iframe><p>When we install <strong>puppeteer</strong>, it downloads a recent version of <strong>Chrome Browser</strong> or <strong>Chromium</strong>(~170 MB MacOS, ~280MB Windows). You can skip the download by installing <strong>puppeteer-core </strong>rather than <strong>puppeteer. </strong>It doesn’t have any integrated browser. It will use the existing browser rather than installing new one.</p><h3>Let’s Create Something Awesome</h3><p><strong>Puppeteer </strong>will be easy to people who are familiar with other testing frameworks. We’ll create a <strong>Browser</strong> instance, open web pages and manipulate them with <strong>Puppeteer’s API.</strong></p><ol><li><strong>Creating a Application to take Screenshot from a Web Page</strong></li></ol><p>Let’s create a file named screenshot.js and import puppeteer module with require function. Then we’ll write a <strong>anonymous async</strong> function to initiate a <strong>Browser </strong>instance and open a <strong>URL </strong>to capture a screenshot. The code will look like that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/227b03a4335e719d5e465d877259964a/href">https://medium.com/media/227b03a4335e719d5e465d877259964a/href</a></iframe><p>We simply launched a browser and went to <a href="https://www.youtube.com/">https://www.youtube.com</a> and took a Screenshot. Default Viewport size is <strong>800 × 600 px</strong>, Which is little small. That’s why we defined a custom viewport via <strong>setViewport()</strong> function. Now run <strong><em>node screenshot.js</em></strong> in your terminal.</p><p>It will generate a PNG file. In my case output of the program is pretty satisfying.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k0XE3qEadrrh6vKwcLlOnw.png" /></figure><p>Let’s explore more.</p><p>2. <strong>Creating a Application to convert webpages into PDF</strong></p><p>It can be very useful real-time application to convert a <strong>article page</strong> into readable pdf. So, let’s start by creating a new file and naming it <strong>createpdf.js. </strong>Everything will remain same and we will just change one function. We’ll use use <strong>page.pdf() </strong>function instead of <strong>page.screenshot()</strong>. The code will look like that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9786c3589624ab8f99bb22ddeaeb73fa/href">https://medium.com/media/9786c3589624ab8f99bb22ddeaeb73fa/href</a></iframe><p>Run this script via Terminal using command <strong><em>node createpdf.js</em></strong>. Output is satisfying in my case.</p><p>We saw two of the most basic application <strong>puppeteer</strong>. Now, let’s talk about more advance usage of puppeteer. To create any <strong>Dynamic</strong> app, we need data. Like, you wanna build a News app. In that case you need News data. There are lots of <strong>API </strong>which will provide <strong>JSON </strong>data for your project but what if you don’t want to use external API. Answer is <strong>Web Scraping. Web Scraping </strong>is a process to collect information from web. There are mainly two steps to Scrap a Website.</p><ol><li><strong>Scrap full source code of a website.</strong></li><li><strong>Grab required data from full source code.</strong></li></ol><p>We’re gonna use <strong>Puppeteer</strong> to scrap source code and <strong>Cheerio</strong> to filter data. <strong>Cheerio </strong>is efficient library to filter data with <strong>jQuery </strong>like syntax.</p><p>We’ll scrap google news to grab news data…</p><p>First, create a new file and name it <strong>newapi.js. </strong>and then Install <strong>cheerio</strong> via terminal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3df989e7ffd8b68677ba31b31c098c80/href">https://medium.com/media/3df989e7ffd8b68677ba31b31c098c80/href</a></iframe><p>It will install cheerio in your project directory. Let’s say we want to collect headlines and images from <strong>Google News. </strong>Now go to google news page and open <strong>DevTool </strong>by clicking ctrl+shift+i. Now select<strong> headline</strong> text of a newsbox and right click on it then click on inspect. You can see the source code. Note down the class. In my case I found <strong>“JheGif nDgy9d”</strong> as the className of this element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4T6x9Ek6cCOoTJC6tgOVQ.png" /></figure><p>Now, do same for images. I didn’t found a className for images. So, I noted down the class of it’s parent div element, which is <strong>“KNcnob”. </strong>Finally, we’re ready to scrap <strong>Google news.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1087fb5db0608f093d42ad85d6855668/href">https://medium.com/media/1087fb5db0608f093d42ad85d6855668/href</a></iframe><p>In this code we imported two module, <strong>Puppeteer </strong>and <strong>Cheerio. </strong>Defined default URL for <strong>Google news</strong> tab. In anonymous function, we initiate a browser and then went to <strong>URL</strong> via <strong>page.goto() </strong>function.<strong> page.content()</strong> function helped us to get source code. Now, run this program with <strong><em>node newsapi.js </em></strong>command. Result will be like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A1go7AOD4uYQvbu1iJo84A.png" /></figure><p>But this unstructured and dirty, right? Here comes, <strong>cheerio. </strong>We’ll use it to filter our required data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74d73ee8dc0a5fc15b52bff96747c91d/href">https://medium.com/media/74d73ee8dc0a5fc15b52bff96747c91d/href</a></iframe><p>Everything is just same before <strong>line 14. </strong>We loaded source code of <strong>Google News </strong>page to filter data. Defining a empty array is important to collect filtered data. We noted down the classes of <strong>Headline </strong>and<strong> Image. </strong>So, we’e looping through every appearance of this class and extracting it’s inner text via <strong>cheerio text() </strong>function and extracting image source via <strong>attr() </strong>function. and adding values to <strong>result </strong>array. Finally printing <strong>result </strong>via console.log() function. Run this script again boom!!! you got a well structured <strong>JSON data</strong> like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p26igbbl8bxWt5bry_W_PQ.png" /></figure><h3>Conclusion</h3><p>In this article I tried to explain most basic application of <strong>Puppeteer </strong>along wit it’s most advance level application. Web scraping is the secret technique used by every Data Delivery Website, to collect data from Internet and pass it to the user. Now, you can write your own <strong>Web scrapper </strong>to collect data from internet and use it for your own application.</p><p><strong>Happy Coding!!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cd2a1e3fcdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Roadmap to the Optical Character Recognition with Python and Tesseract]]></title>
            <link>https://medium.com/geekculture/a-guide-to-ocr-and-tesseract-engine-75195210f4f7?source=rss-f658f9a6a27a------2</link>
            <guid isPermaLink="false">https://medium.com/p/75195210f4f7</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[tesseract]]></category>
            <dc:creator><![CDATA[Satadeep Dasgupta]]></dc:creator>
            <pubDate>Fri, 18 Jun 2021 04:27:31 GMT</pubDate>
            <atom:updated>2021-06-18T19:36:52.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FsXzwCaJBR5q47KHumcwMQ.jpeg" /></figure><p><strong>Optical character recognition</strong> or <strong>optical character reader</strong> (<strong>OCR</strong>) is the electronic or mechanical conversion of images of typed, handwritten or printed text into machine-encoded text, whether from a scanned document, a photo of a document, a scene-photo or from subtitle text superimposed on an image. In more simple way, <strong>OCR </strong>is a process of extracting text from images. You may have already scene many of it’s real-world applications like text extraction from documents, collecting data from Invoices, passport documents, bank statements, computerized receipts, business cards, mail, printouts of static-data, or any suitable documentation. It is a common way of digitizing printed texts so that they can be electronically edited, searched, stored more compactly, displayed on-line, and used in machine processes.</p><h3>A brief history</h3><p>Primarily Optical character recognition was used for modifying <strong>Telegraphy </strong>creating reading devices for blind persons. It was 1914 when <strong>Emanuel Goldberg </strong>invented a machine that read text characters and abled to convert them into <strong>Telegraph code. </strong>Concurrently, Edmund Fournier d’Albe developed the Octophone, a handheld scanner that when moved across a printed page, produced tones that corresponded to specific letters or characters.</p><p>In the late 1920s and into the 1930s Emanuel Goldberg developed what he called a “Statistical Machine” for searching microfilm archives using an optical code recognition system. In 1931 he was granted USA Patent number 1,838,389 for the invention. The patent was acquired by IBM.</p><p>Later in 1900’s, there was a numerous inventions on <strong>Optical Character Recognition. </strong>One of the most popular and groundbreaking invention is Photocopy or Xerox.</p><h3>Modern Optical Character Recognition</h3><p>Early versions needed to be trained with images of each character, and worked on one font at a time. Advanced systems capable of producing a high degree of recognition accuracy for most fonts are now common, and with support for a variety of digital image file format inputs. Some systems are capable of reproducing formatted output that closely approximates the original page including images, columns, and other non-textual components.</p><p>Modern OCR as a process generally consists of several sub-processes to perform as accurately as possible. The sub-processes are:</p><ol><li><strong>Pre-Processing of the image</strong></li><li><strong>Text Localization</strong></li><li><strong>Character Segmentation</strong></li><li><strong>Character Recognition</strong></li><li><strong>Post-Processing</strong></li></ol><p>The list of sub-processes can differ depending on situation and requirements but rough outline of total process will be like that. The aim of this whole process is to identify each and every word correctly and give result as accurate as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*VsOnKsBAfEC-dsj8GtPxwg.png" /></figure><p>So, we are gonna program this whole thing, right? NO, programing this whole process isn’t a piece of cake and will take lot of years. Hopefully, there is a pre-programmed Engine named “Tesseract” which will help use execute this whole task easily.</p><h3>Tesseract</h3><p>“<strong><em>Tesseract</em></strong><em> is an optical character recognition engine for various operating systems. It is free software, released under the Apache License. Originally developed by Hewlett-Packard as proprietary software in the 1980s, it was released as open source in 2005 and development has been sponsored by Google since 2006.</em></p><p><em>In 2006, Tesseract was considered one of the most accurate open-source OCR engines then available.</em>”</p><p>There are lots of <strong>OCR </strong>engines available in market but None of them are efficient like <strong>Tesseract. </strong>Either they are not free or they are frustrating to handle. Even though it can be hard to integrate T<strong>esseract </strong>but still better than many available options. By default, <strong>Tesseract </strong>comes as a command line software but there are many Third party options for <strong>GUI Tesseract </strong>Software. It can be used via <strong>API </strong>for binding it with other popular programming languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*moqYZ8dMlglh-ohXTECRhg.png" /></figure><p><strong>Tesseract 4</strong> has a new neural network subsystem configured as a text line recognizer. It’s actually a re-implementation of <strong>OCRopus Python-based LSTM</strong> but re-written in <strong>C++</strong>.</p><p>In this whole character recognition process, we generally use a <strong>Convolutional Neural Network or CNN. </strong>We can consider a text as a sequence of characters and for solving such problems we typically use <strong>LSTM </strong>or <strong>Long Short Term Memory networks. </strong>It’s a popular form of <strong>RNN</strong> or <strong>Recurrent Neural Networks.</strong></p><h3>How Tesseract 4 works?</h3><p>Though <strong>LSTMs </strong>are great at learning sequence but there is a major drawback. It gets slow when the number of states is too large. By here, we can assume that we should prefer long sequences more than short sequences with too many classes. Tesseract developed from a fork of <strong>LSMT</strong> in <strong>C++ </strong>called <strong>CLSMT. </strong>Previous version of <strong>Tesseract </strong>was primely dependent on three main sub-process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*q_W3moLqMH8ER8ZonctqpA.png" /></figure><ol><li>Word finding</li><li>Line finding</li><li>Character Classification</li></ol><p>The main purpose of republishing <strong>Tesseract </strong>was cleaning the code and implementing <strong>LSTM </strong>Model.</p><h3>Tesseract Installation</h3><p>Installing <strong>Tesseract</strong> on Windows PC is pretty simple. Download precompiled binary from <a href="http://tesseract-ocr-w64-setup-v4.1.0.20190314.exe/">here</a>. Don’t forget to add path of installation to <strong>PATH</strong> variable. Now, check the installation via</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ce236b3f1fd7de9655652d5130e0cc0/href">https://medium.com/media/9ce236b3f1fd7de9655652d5130e0cc0/href</a></iframe><p>If this command runs without any error then installation is correct. We’re gonna walk through some python implementation. So, we have to install <strong>pytesseract </strong>as a python wrapper for <strong>Tesseract</strong> and <strong>OpenCV</strong> for pre-processing. We’ll use <strong>pip</strong> installer for installing libraries.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b0333d4a87e7c0f6d49f648d9f0aba5/href">https://medium.com/media/8b0333d4a87e7c0f6d49f648d9f0aba5/href</a></iframe><p>I’ll use this simple document image for extracting text from it. You can download it from <a href="https://github.com/satadeep3927/color-recognization/blob/master/main.jpg">here</a>.</p><p>let’s write a simple code to extract text from given image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a80321ef25a9fab9e36ec01e4248d464/href">https://medium.com/media/a80321ef25a9fab9e36ec01e4248d464/href</a></iframe><p>We used <strong>OpenCV</strong> imread() function to convert image to binary data and then we used <strong>Tesseract</strong> image_to_string() function to extract text from binary image data. Pretty simple, right? but wait we discussed about Pre-processing. Where is that and why that? Extracting text from non-processed image can be a big mistake especially when image is colorful or it’s background is noisy. So, we have to add a pre-processing before extracting text from it. There are many options to pre-process image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23ec9b2d23c2c9849df70ab8068dc95e/href">https://medium.com/media/23ec9b2d23c2c9849df70ab8068dc95e/href</a></iframe><p>We can use any of them. It’s depends on your input image. I’m using document type file. That’s why decolorizing is a good option to go. So, we have to add get_greyscale() function to decolorize image. Final out come will be like that…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14a3c6f7370b72ec630fbd87756b0dd8/href">https://medium.com/media/14a3c6f7370b72ec630fbd87756b0dd8/href</a></iframe><h3>Conclusion</h3><p>It’s a very basic guide for <strong>OCR </strong>and <strong>Tesseract Engine. </strong>There are many more things you can do with <strong>Tesseract </strong>but to do that kind of staffs, you need to know basics. Stuck with basic for few weeks and you’ll find it easy and handy. Then you can start doing cool staffs with <strong>Tesseract</strong></p><p><strong>Happy coding!!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75195210f4f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/a-guide-to-ocr-and-tesseract-engine-75195210f4f7">A Roadmap to the Optical Character Recognition with Python and Tesseract</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML based Color Detection with Python]]></title>
            <link>https://satadeepdasgupta.medium.com/ml-based-color-detection-with-python-3f067baa9e36?source=rss-f658f9a6a27a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f067baa9e36</guid>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Satadeep Dasgupta]]></dc:creator>
            <pubDate>Thu, 17 Jun 2021 12:25:11 GMT</pubDate>
            <atom:updated>2021-06-19T03:46:40.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SwG7wQfOcOu17AO3APBpGw.jpeg" /></figure><p>In this article, we’re gonna learn about ML based color detection with a basic level application which will help us to detect colors in image. The workflow of our application will be like that:</p><p>Take path of image file&gt; open a window to select section &gt; return name and RGB color code</p><p>Web developers and designers know the importance of RGB value. So, it’s gonna be a easy but very useful implementation of Computer vision and color recognition. Now, let’s get started…</p><p>For our project we’ll use OpenCV and Pandas library.</p><h3>OpenCV</h3><p><strong>“<em>OpenCV</em></strong><em> (Open Source Computer Vision Library) is a library of programming functions mainly aimed at real-time computer vision. Originally developed by Intel, it was later supported by Willow Garage then Itseez (which was later acquired by Intel). The library is cross-platform and free for use under the open-source Apache 2 License. Starting with 2011, OpenCV features GPU acceleration for real-time operations.</em>”</p><p>Simply OpenCV is a project to help us to process images and videos. Many popular software company uses it for their applications. Hopefully, there is a standard OpenCV library for python. You can easily install it with pip installer.</p><pre>pip install opencv-python</pre><p>It will install latest version of Opencv library. If you haven’t pip installed in your pc then go to this link <a href="https://www.geeksforgeeks.org/how-to-install-pip-on-windows/">https://www.geeksforgeeks.org/how-to-install-pip-on-windows/</a></p><h3>Pandas</h3><p>“<strong><em>pandas</em></strong><em> is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool,<br>built on top of the Python programming language.</em>”</p><p>Panda is a opensource library used for data analysis. It’s a very popular tool among experts and pro developers. We’re gonna use it for analyzing data sets. You can install it with the help of pip installer</p><pre>pip install pandas</pre><p>It’ll be a little better to know fundamentals of OpenCV library before implementing it in our application. So, we are gonna build a camera application with OpenCV. At first we will import cv2 to library and then we will use it’s VideoCapture() function to capture video. Then we will use a while loop read every frame and show it in a default OpenCV window. User has to will press Esc key to end program. Let’s write all together.</p><pre>#importing OpenCV<br>import cv2 as opencv</pre><pre>#capturing video<br>capture = opencv.VideoCapture(0)</pre><pre>while(1):</pre><pre>#reading every frame of video<br>r, f = capture.read()</pre><pre>#showing each frame in a OpenCV Window<br>opencv.imshow(&#39;frame&#39;,f)</pre><pre>#defining exit key as Esc as it&#39;s code is 27<br>if opencv.waitKey(1) &amp; 0xFF== 27:</pre><pre>break</pre><pre>capture.release()</pre><pre>#destroying OpenCV windows<br>opencv.destroyAllWindows()</pre><p>I think Code is pretty self explanatory with comments. let’s jump to the Actual program</p><p>We need a dataset to recognize color names and Hex code. For demonstration purpose we’re gonna use a csv file of 1000 examples. You can download it from <a href="https://github.com/satadeep3927/color-recognization/blob/master/dataset.csv">here</a>.</p><ol><li>Import required libraries like NumPy, Pandas and OpenCV.</li></ol><pre>import numpy</pre><pre>import pandas</pre><pre>import cv2 as opencv</pre><p>2. Taking user Input for image file location and reading it with OpenCV imread() function.</p><pre>image = opencv.imread(input(&quot;Input a File location: &quot;))</pre><p>3. We’ve unstructured dataset as csv file. let’s make it more readable with pandas read_csv() function. For using it we have to define a list with its column names. and then we’ll pass this list as a argument of read_csv() function.</p><pre>#defining column names<br>index = [&quot;color&quot;,&quot;color_name&quot;,&quot;hex&quot;,&quot;R&quot;,&quot;G&quot;,&quot;B&quot;]</pre><pre>#reading dataset file and structuring it<br>dataset = pandas.read_csv(&quot;dataset.csv&quot;, names=index, header=None)</pre><p>4. Now we’re gonna some global variables for functions.</p><pre>clickstate = False</pre><pre>r=0</pre><pre>g=0</pre><pre>b=0</pre><pre>position_x = 0</pre><pre>position_y = 0</pre><p>5. We will create a function that will take arguments of R,G,B values and find a name for this values. Pandas loc() function will help us to find color name.</p><pre>def recognizer(R,G,B):</pre><pre>minimum = 1000</pre><pre>for i in range(len(dataset)):</pre><pre>d = abs(R - int(dataset.loc[i,&quot;R&quot;])) + abs(G - int(dataset.loc[i, &quot;G&quot;])) + abs(B - int(dataset.loc[i, &quot;B&quot;]))</pre><pre>if(d&lt;=minimum):</pre><pre>minimum = d</pre><pre>cname = dataset.loc[i, &quot;color_name&quot;]</pre><pre>return cname</pre><p>6. We need to create a Mouse click handler to handle user’s double click on image and get the position of click.</p><pre>def clickhandler(event, x, y,f,p):</pre><pre>if event == opencv.EVENT_LBUTTONDBLCLK:</pre><pre><em>global</em> b,g,r,position_x,position_y, clickstate</pre><pre>clickstate = True</pre><pre>position_x = x</pre><pre>position_y = y</pre><pre>b,g,r = image[y,x]</pre><pre>b = int(b)</pre><pre>g = int(g)</pre><pre>r = int(r)</pre><p>7. We’re gonna create a OpenCV window to open image and set clickhandler function as a Mouse click handler which will be triggered by double click of user.</p><pre>opencv.namedWindow(&#39;Color Recognition Application&#39;)</pre><pre>opencv.setMouseCallback(&#39;Color Recognition Application&#39;, clickhandler)</pre><p>8. Now we’ll write a while loop for detecting color from image. Comments are self explanatory.</p><pre>while(1):</pre><pre>opencv.imshow(&quot;Color Recognition Application&quot;,image)</pre><pre>if (clickstate):</pre><pre><em>#opencv.rectangle(image, startpoint, endpoint, color, thickness)-1. It fills entire rectangle</em></pre><pre>opencv.rectangle(image,(20,20), (750,60), (b,g,r), -1)</pre><pre><em>#Creating a text string to display color name and RGB value</em></pre><pre>text = recognizer(r,g,b) + &quot;  RGB(&quot;+str(r)+&quot;,&quot;+str(g)+&quot;,&quot;+str(b)+&quot;)&quot;</pre><pre><em>#opencv.putText() function will write data on image</em></pre><pre>opencv.putText(image, text,(50,50),2,0.8,(255,255,255),2,opencv.LINE_AA)</pre><pre><em>#For light colors we will choose black color</em></pre><pre>if(r+g+b&gt;=600):</pre><pre>opencv.putText(image, text,(50,50),2,0.8,(0,0,0),2,opencv.LINE_AA)</pre><pre>clickstate=False</pre><pre><em>#Ends the function when Esc is clicked</em></pre><pre>if opencv.waitKey(20) &amp; 0xFF ==27:</pre><pre>break</pre><p>9. Close the OpenCV window with destroyAllWindows() function.</p><pre>opencv.destroyAllWindows()</pre><p>All together looks like…</p><pre>import numpy</pre><pre>import pandas</pre><pre>import cv2 as opencv</pre><pre>image = opencv.imread(input(&quot;Input a File location: &quot;))</pre><pre>index = [&quot;color&quot;,&quot;color_name&quot;,&quot;hex&quot;,&quot;R&quot;,&quot;G&quot;,&quot;B&quot;]</pre><pre>dataset = pandas.read_csv(&quot;dataset.csv&quot;, names=index, header=None)</pre><pre>clickstate = False</pre><pre>r=0</pre><pre>g=0</pre><pre>b=0</pre><pre>position_x = 0</pre><pre>position_y = 0</pre><pre>def recognizer(R,G,B):</pre><pre>minimum = 1000</pre><pre>for i in range(len(dataset)):</pre><pre>d = abs(R - int(dataset.loc[i,&quot;R&quot;])) + abs(G - int(dataset.loc[i, &quot;G&quot;])) + abs(B - int(dataset.loc[i, &quot;B&quot;]))</pre><pre>if(d&lt;=minimum):</pre><pre>minimum = d</pre><pre>cname = dataset.loc[i, &quot;color_name&quot;]</pre><pre>return cname</pre><pre>def clickhandler(event, x, y,f,p):</pre><pre>if event == opencv.EVENT_LBUTTONDBLCLK:</pre><pre><em>global</em> b,g,r,position_x,position_y, clickstate</pre><pre>clickstate = True</pre><pre>position_x = x</pre><pre>position_y = y</pre><pre>b,g,r = image[y,x]</pre><pre>b = int(b)</pre><pre>g = int(g)</pre><pre>r = int(r)</pre><pre>opencv.namedWindow(&#39;Color Recognition Application&#39;)</pre><pre>opencv.setMouseCallback(&#39;Color Recognition Application&#39;, clickhandler)</pre><pre>while(1):</pre><pre>opencv.imshow(&quot;Color Recognition Application&quot;,image)</pre><pre>if (clickstate):</pre><pre><em>#opencv.rectangle(image, startpoint, endpoint, color, thickness)-1. It fills entire rectangle</em></pre><pre>opencv.rectangle(image,(20,20), (750,60), (b,g,r), -1)</pre><pre><em>#Creating a text string to display color name and RGB value</em></pre><pre>text = recognizer(r,g,b) + &quot;  RGB(&quot;+str(r)+&quot;,&quot;+str(g)+&quot;,&quot;+str(b)+&quot;)&quot;</pre><pre><em>#opencv.putText() function will write data on image</em></pre><pre>opencv.putText(image, text,(50,50),2,0.8,(255,255,255),2,opencv.LINE_AA)</pre><pre><em>#For light colors we will choose black color</em></pre><pre>if(r+g+b&gt;=600):</pre><pre>opencv.putText(image, text,(50,50),2,0.8,(0,0,0),2,opencv.LINE_AA)</pre><pre>clickstate=False</pre><pre><em>#Ends the function when Esc is clicked</em></pre><pre>if opencv.waitKey(20) &amp; 0xFF ==27:</pre><pre>break</pre><pre>opencv.destroyAllWindows()</pre><p>Now run the program and see magic.</p><h3>Conclusion</h3><p>This article describes a very basic application of powerful OpenCV and Pandas library. We can research on it and create more powerful and awesome application with these library.</p><p>Happy coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f067baa9e36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type effect with pure CSS]]></title>
            <link>https://satadeepdasgupta.medium.com/type-effect-with-pure-css-8836e9fbd6e1?source=rss-f658f9a6a27a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8836e9fbd6e1</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[css3]]></category>
            <dc:creator><![CDATA[Satadeep Dasgupta]]></dc:creator>
            <pubDate>Fri, 26 Feb 2021 17:47:01 GMT</pubDate>
            <atom:updated>2021-02-26T18:06:56.833Z</atom:updated>
            <content:encoded><![CDATA[<h3>Typing effect with pure CSS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*A-Z2FXeWJcSG1mHe3iXC6w.gif" /></figure><p>Typing effect is one of the fanciest thing you can do css easily. In this short article I’ll explain whole thing. So, don’t waste time and create a project folder and inside it, create two files.</p><ol><li>index.html(your home page)</li><li>style.css(your stylesheet)</li></ol><p>Open index.html and paste this code.</p><pre>&lt;!DOCTYPE html&gt;</pre><pre>&lt;html lang=&quot;en&quot;&gt;</pre><pre>&lt;head&gt;</pre><pre>&lt;meta charset=&quot;UTF-8&quot;&gt;</pre><pre>&lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;</pre><pre>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>&lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;/&gt;</pre><pre>&lt;title&gt;CSS  TYPE EFFECT | NO JAVASCRIPT&lt;/title&gt;</pre><pre>&lt;/head&gt;</pre><pre>&lt;body&gt;</pre><pre>&lt;div&gt;&lt;h1&gt;CSS is beautiful!&amp;nbsp;&lt;/h1&gt;&lt;/div&gt;</pre><pre>&lt;/body&gt;</pre><pre>&lt;/html&gt;</pre><p>Here is nothing like rocket-science. We simply created a div element a inside it we created h1 element with some sample text. First part is now completed here…</p><p>Now open your Style sheet and paste this code snppet</p><pre>body{</pre><pre>background-color: black;</pre><pre>color: white;</pre><pre>height: 100vh;</pre><pre>overflow: hidden;</pre><pre>display: flex;</pre><pre>justify-content: center;</pre><pre>}</pre><pre>h1{</pre><pre>height: fit-content;</pre><pre>margin-right: auto;</pre><pre>font-size: 3.4em;</pre><pre>font-family: Georgia, &#39;Times New Roman&#39;, Times, serif;</pre><pre>background: linear-gradient(90deg,red,blue);</pre><pre>color: transparent;<br>/* white-space should be no-wrap to prevent line break */</pre><pre>white-space: nowrap;</pre><pre>background-clip: text;</pre><pre>-webkit-background-clip: text;</pre><pre>border-right: 1px solid white;</pre><pre>overflow-x: hidden;<br>/* first parameter of steps()</pre><pre>should be the number character in text*/</pre><pre>animation: typer 3.5s steps(18, end),blink .75s 3.5s step-end infinite;</pre><pre>}</pre><pre>div{</pre><pre>height: fit-content;</pre><pre>margin: auto;</pre><pre>min-width: 300px;</pre><pre>}</pre><pre>@keyframes typer {</pre><pre>from{width: 0;</pre><pre>}</pre><pre>to{width: 100%;</pre><pre>}</pre><pre>}</pre><pre>@keyframes blink {</pre><pre>from, to {border-color: transparent;}</pre><pre>50% {border-color: white;}</pre><pre>}</pre><p>Now run the code in your browser. it’s looking awesome right?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8836e9fbd6e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>