<?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 Yıldıray Kuru on Medium]]></title>
        <description><![CDATA[Stories by Yıldıray Kuru on Medium]]></description>
        <link>https://medium.com/@yldrykuru?source=rss-dcdb0ac6f0f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A4p__kvBuZ9EM2Rg-MMF_w.png</url>
            <title>Stories by Yıldıray Kuru on Medium</title>
            <link>https://medium.com/@yldrykuru?source=rss-dcdb0ac6f0f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:03:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yldrykuru/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[Optimize JPEGs with Python: Reduce File Size by 40% Without Quality Loss]]></title>
            <link>https://yldrykuru.medium.com/optimize-jpegs-with-python-reduce-file-size-by-40-without-quality-loss-e27d6343e6ea?source=rss-dcdb0ac6f0f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e27d6343e6ea</guid>
            <category><![CDATA[image-compression]]></category>
            <category><![CDATA[zstandard]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Yıldıray Kuru]]></dc:creator>
            <pubDate>Thu, 12 Jun 2025 13:27:25 GMT</pubDate>
            <atom:updated>2025-06-12T13:27:25.383Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X5jnxl8KaMGAXItjs59TUA.png" /></figure><h3>Introduction</h3><p>Most people assume that JPEG files, being already compressed, can’t be reduced any further. But that’s not always the case. With a few smart and efficient steps, it’s possible to significantly shrink JPEG sizes — without any noticeable loss in quality. In this article, we’ll walk through how we reduced JPEG file sizes by up to 40% using Python, with a real-world example.</p><h3>The Problem With “Already Compressed” JPEGs</h3><p>JPEG is a lossy format, meaning it’s already compressed and optimized for space. That said, many JPEGs still contain unnecessary metadata (like GPS or camera info), use suboptimal compression parameters, or are just exported inefficiently.</p><p>Our test case:</p><ul><li><strong>Original size</strong>: 30 MB</li><li><strong>Goal</strong>: Reduce size without losing visual quality</li></ul><h3>Python Implementation</h3><pre>import os<br>from PIL import Image<br>import zstandard as zstd<br>import piexif<br><br>def optimize_jpeg(input_path: str, temp_path: str):<br>    image = Image.open(input_path)<br>    if &quot;exif&quot; in image.info:<br>        piexif.remove(input_path)<br>    image.save(temp_path, format=&quot;JPEG&quot;, quality=85, optimize=True)<br>    print(f&quot;[1] Optimized JPEG: {temp_path}&quot;)<br><br>def compress_zstd(input_path: str, output_path: str, level: int = 19):<br>    with open(input_path, &quot;rb&quot;) as f:<br>        jpeg_data = f.read()<br>    cctx = zstd.ZstdCompressor(level=level)<br>    compressed = cctx.compress(jpeg_data)<br>    with open(output_path, &quot;wb&quot;) as f:<br>        f.write(compressed)<br>    print(f&quot;[2] Zstd Compressed: {output_path} ({len(compressed)/1024:.2f} KB)&quot;)<br><br>def full_pipeline(original_jpeg: str):<br>    basename = os.path.splitext(original_jpeg)[0]<br>    temp_optimized = f&quot;{basename}_optimized.jpg&quot;<br>    output_zstd = f&quot;{basename}.jpg.zst&quot;<br>    optimize_jpeg(original_jpeg, temp_optimized)<br>    compress_zstd(temp_optimized, output_zstd)<br>    os.remove(temp_optimized)<br>    print(f&quot;[\u2713] Done: {output_zstd}&quot;)<br><br>full_pipeline(&quot;image-file.jpg&quot;)</pre><h3>Visual Results</h3><h3>File Size Comparison</h3><pre>| Stage              | File Size     | Notes                                |<br>|--------------------|---------------|--------------------------------------|<br>| Original           | 30,000 KB     | Exported from Lightroom              |<br>| Optimized JPEG     | ~22,000 KB    | `quality=85`, `optimize=True`        |<br>| Metadata Removed   | ~20,000 KB    | No EXIF, no GPS                      |<br>| Zstd Compressed    | 18,282 KB     | Final result (~39% reduction)        |</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*szXqsnSTC3073WZQ0XqjOA.png" /></figure><h3>Decompression</h3><p>To restore the original JPEG from .zst:</p><pre>def decompress_zstd(input_path: str, output_path: str):<br>    with open(input_path, &quot;rb&quot;) as f:<br>        compressed = f.read()<br>    dctx = zstd.ZstdDecompressor()<br>    jpeg_data = dctx.decompress(compressed)<br>    with open(output_path, &quot;wb&quot;) as f:<br>        f.write(jpeg_data)<br>    print(f&quot;[\u2713] Decompressed: {output_path}&quot;)<br><br>decompress_zstd(&quot;image-file.zst&quot;, &quot;image-file.jpg&quot;)</pre><h3>Final Thoughts</h3><p>This approach is especially useful if you:</p><ul><li>Deal with image-heavy archives</li><li>Run an e-commerce or CMS platform</li><li>Need better transfer speeds without adopting new image formats</li></ul><p>Of course, modern formats like WebP or AVIF are even more efficient. But when JPEG is required, this strategy offers an elegant and compatible solution.</p><h3>Let’s Talk</h3><p><strong>💬 Feedback, Ideas, or Bug Reports?</strong> Tried something similar? Got questions, feedback, or ideas for improvement? <strong>Drop a comment below</strong> — I’d love to hear your thoughts and learn from your experiences!</p><p>Let’s keep the conversation going. 🗣️✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e27d6343e6ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From 7.6GB CSV to 0.42GB Parquet: Chunked Conversion with Python]]></title>
            <link>https://yldrykuru.medium.com/from-7-6gb-csv-to-0-42gb-parquet-production-ready-big-data-solution-d09dc1f1bbd8?source=rss-dcdb0ac6f0f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d09dc1f1bbd8</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[parquet]]></category>
            <dc:creator><![CDATA[Yıldıray Kuru]]></dc:creator>
            <pubDate>Mon, 02 Jun 2025 11:24:15 GMT</pubDate>
            <atom:updated>2026-11-20T15:44:41.181Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jc1d7Vff5bwahZETQSJIXw.png" /></figure><h3>📊 The Problem: When “Out of Memory” Strikes…</h3><p>Last week I needed to analyze a 7.6GB CSV file. When I tried the classic pandas approach:</p><pre>df = pd.read_csv(&quot;huge_file.csv&quot;)  # ❌ MemoryError!</pre><p>To get around this, I built a chunked conversion pipeline with pandas and PyArrow. The result: a 94.5% smaller file that is far easier to query.</p><blockquote>TLDR: 7.6GB CSV → 0.42GB Parquet, converted in chunks and queried with DuckDB</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FpNNYCtnlOyOPdjjtIY0UQ.png" /></figure><h3>🔧 Solution 1: Solving Memory Issues with Chunked Processing</h3><p>The first step was to process the large file by breaking it into smaller chunks. Here’s the main.py script I developed:</p><pre>import pandas as pd<br>import os<br>import pyarrow as pa<br>import pyarrow.parquet as pq<br>from pathlib import Path<br>chunk_size = 50000<br>csv_file = &quot;OP_DTL_GNRL_PGYR2023_P01302025_01212025.csv&quot;<br>parquet_file = &quot;OP_DTL_GNRL_PGYR2023_P01302025_01212025.parquet&quot;<br>temp_dir = &quot;temp_chunks&quot;<br>print(f&quot;Starting conversion of {csv_file} to {parquet_file}&quot;)<br>print(f&quot;Processing in chunks of {chunk_size:,} rows&quot;)<br>Path(temp_dir).mkdir(exist_ok=True)<br>if os.path.exists(parquet_file):<br>    os.remove(parquet_file)<br>chunk_num = 0<br>total_rows_processed = 0<br>chunk_files = []<br>try:<br>    csv_reader = pd.read_csv(<br>        csv_file,<br>        chunksize=chunk_size,<br>        low_memory=False,<br>        dtype=str  # 🔑 Important: Read all data as strings<br>    )<br>    <br>    for chunk in csv_reader:<br>        chunk_num += 1<br>        rows_in_chunk = len(chunk)<br>        total_rows_processed += rows_in_chunk<br>        <br>        print(f&quot;Processing chunk {chunk_num}: {rows_in_chunk:,} rows&quot;)<br>        <br>        temp_file = f&quot;{temp_dir}/chunk_{chunk_num:04d}.parquet&quot;<br>        chunk.to_parquet(temp_file, compression=&quot;zstd&quot;, index=False)<br>        chunk_files.append(temp_file)<br>        <br>        del chunk  # Clean up memory<br>        <br>        if chunk_num % 10 == 0:<br>            print(f&quot;Completed {chunk_num} chunks...&quot;)<br>    # Combine chunks<br>    tables = []<br>    print(&quot;Reading chunk files...&quot;)<br>    <br>    for i, chunk_file in enumerate(chunk_files):<br>        if (i + 1) % 20 == 0:<br>            print(f&quot;Reading chunk file {i + 1}/{len(chunk_files)}&quot;)<br>        table = pq.read_table(chunk_file)<br>        tables.append(table)<br>    <br>    print(&quot;Concatenating all chunks...&quot;)<br>    final_table = pa.concat_tables(tables, promote_options=&#39;default&#39;)<br>    pq.write_table(final_table, parquet_file, compression=&quot;zstd&quot;)<br>    <br>    print(f&quot;\nConversion complete!&quot;)<br>    print(f&quot;Total rows processed: {total_rows_processed:,}&quot;)<br>    print(f&quot;Output file: {parquet_file}&quot;)<br>    <br>    if os.path.exists(parquet_file):<br>        file_size = os.path.getsize(parquet_file) / (1024**3)<br>        print(f&quot;Output file size: {file_size:.2f} GB&quot;)<br>    <br>    print(&quot;Cleaning up temporary files...&quot;)<br>    for chunk_file in chunk_files:<br>        os.remove(chunk_file)<br>    os.rmdir(temp_dir)<br>    print(&quot;Cleanup complete!&quot;)<br>except Exception as e:<br>    print(f&quot;Error during conversion: {str(e)}&quot;)<br>    print(&quot;Try reducing the chunk_size if you&#39;re still running out of memory&quot;)<br>    try:<br>        for chunk_file in chunk_files:<br>            if os.path.exists(chunk_file):<br>                os.remove(chunk_file)<br>        if os.path.exists(temp_dir):<br>            os.rmdir(temp_dir)<br>    except:<br>        pass</pre><h3>🎯 Critical Success Factors:</h3><ol><li>dtype=str: Keeps the schema identical across chunks (cast numeric columns back when querying)</li><li>compression=&quot;zstd&quot;: Strong compression with fast decompression</li><li>Chunk size: 50,000 rows worked well for this dataset; tune it to your available RAM</li><li>Memory cleanup: Free each chunk after writing it</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PWGJ7y2aj3U6stpHhSAMag.png" /></figure><h3>🔍 Solution 2: A Simple Search Tool</h3><p>To quickly query the Parquet file, I developed search_parquet.py:</p><pre>import pandas as pd<br>import sys<br>def search_parquet(parquet_file, column=None, value=None, contains=None, limit=10):<br>    print(f&quot;Loading parquet file: {parquet_file}&quot;)<br>    <br>    try:<br>        df = pd.read_parquet(parquet_file)<br>        print(f&quot;Total rows: {len(df):,}&quot;)<br>        print(f&quot;Total columns: {len(df.columns)}&quot;)<br>        print()<br>        <br>        if column is None and value is None and contains is None:<br>            print(&quot;Column names:&quot;)<br>            for i, col in enumerate(df.columns, 1):<br>                print(f&quot;{i:2}. {col}&quot;)<br>            print()<br>            print(f&quot;First {limit} rows:&quot;)<br>            print(df.head(limit))<br>            return<br>        <br>        if column and column not in df.columns:<br>            print(f&quot;Error: Column &#39;{column}&#39; not found!&quot;)<br>            print(&quot;Available columns:&quot;)<br>            for col in df.columns:<br>                print(f&quot;  - {col}&quot;)<br>            return<br>        <br>        if column and value:<br>            filtered_df = df[df[column] == value]<br>            print(f&quot;Exact match for {column} = &#39;{value}&#39;: {len(filtered_df):,} rows&quot;)<br>        elif column and contains:<br>            filtered_df = df[df[column].str.contains(str(contains), case=False, na=False)]<br>            print(f&quot;Contains search for {column} containing &#39;{contains}&#39;: {len(filtered_df):,} rows&quot;)<br>        else:<br>            print(&quot;Please specify both column and value/contains parameters&quot;)<br>            return<br>        <br>        if len(filtered_df) &gt; 0:<br>            print(f&quot;\nFirst {min(limit, len(filtered_df))} results:&quot;)<br>            print(filtered_df.head(limit))<br>        else:<br>            print(&quot;No results found!&quot;)<br>            <br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)<br>def interactive_search():<br>    parquet_file = &quot;OP_DTL_GNRL_PGYR2023_P01302025_01212025.parquet&quot;<br>    <br>    print(&quot;=== Parquet Data Search Tool ===&quot;)<br>    print(&quot;Commands:&quot;)<br>    print(&quot;  info - Show basic info and column names&quot;)<br>    print(&quot;  search &lt;column&gt; &lt;value&gt; - Exact search&quot;)<br>    print(&quot;  contains &lt;column&gt; &lt;text&gt; - Text contains search&quot;)<br>    print(&quot;  exit - Quit&quot;)<br>    print()<br>    <br>    try:<br>        df = pd.read_parquet(parquet_file)<br>        print(f&quot;Loaded: {len(df):,} rows, {len(df.columns)} columns&quot;)<br>        print()<br>    except Exception as e:<br>        print(f&quot;Error loading file: {e}&quot;)<br>        return<br>    <br>    while True:<br>        try:<br>            cmd = input(&quot;Enter command: &quot;).strip().split()<br>            <br>            if not cmd or cmd[0] == &quot;exit&quot;:<br>                break<br>            elif cmd[0] == &quot;info&quot;:<br>                search_parquet(parquet_file)<br>            elif cmd[0] == &quot;search&quot; and len(cmd) &gt;= 3:<br>                column = cmd[1]<br>                value = &quot; &quot;.join(cmd[2:])<br>                search_parquet(parquet_file, column=column, value=value)<br>            elif cmd[0] == &quot;contains&quot; and len(cmd) &gt;= 3:<br>                column = cmd[1]<br>                text = &quot; &quot;.join(cmd[2:])<br>                search_parquet(parquet_file, column=column, contains=text)<br>            else:<br>                print(&quot;Invalid command. Use: info, search &lt;column&gt; &lt;value&gt;, contains &lt;column&gt; &lt;text&gt;, or exit&quot;)<br>        except KeyboardInterrupt:<br>            break<br>        except Exception as e:<br>            print(f&quot;Error: {e}&quot;)<br>    <br>    print(&quot;Goodbye!&quot;)<br>if __name__ == &quot;__main__&quot;:<br>    if len(sys.argv) == 1:<br>        interactive_search()<br>    elif len(sys.argv) &gt;= 2 and sys.argv[1] == &quot;info&quot;:<br>        search_parquet(&quot;OP_DTL_GNRL_PGYR2023_P01302025_01212025.parquet&quot;)<br>    elif len(sys.argv) &gt;= 4 and sys.argv[1] == &quot;search&quot;:<br>        column = sys.argv[2]<br>        value = &quot; &quot;.join(sys.argv[3:])<br>        search_parquet(&quot;OP_DTL_GNRL_PGYR2023_P01302025_01212025.parquet&quot;, column=column, value=value)<br>    elif len(sys.argv) &gt;= 4 and sys.argv[1] == &quot;contains&quot;:<br>        column = sys.argv[2]<br>        text = &quot; &quot;.join(sys.argv[3:])<br>        search_parquet(&quot;OP_DTL_GNRL_PGYR2023_P01302025_01212025.parquet&quot;, column=column, contains=text)<br>    else:<br>        print(&quot;Usage:&quot;)<br>        print(&quot;  python search_parquet.py - Interactive mode&quot;)<br>        print(&quot;  python search_parquet.py info - Show file info&quot;)<br>        print(&quot;  python search_parquet.py search &lt;column&gt; &lt;value&gt; - Exact search&quot;)<br>        print(&quot;  python search_parquet.py contains &lt;column&gt; &lt;text&gt; - Contains search&quot;)</pre><h3>🚀 Usage Examples:</h3><pre># Interactive mode<br>python search_parquet.py<br># Quick queries<br>python search_parquet.py search Recipient_State &quot;CA&quot;<br>python search_parquet.py contains Covered_Recipient_Last_Name &quot;Smith&quot;<br>python search_parquet.py info</pre><h3>📈 Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WDt6azrSCeVxkKfdB4KZJw.png" /></figure><h3>Size Comparison:</h3><ul><li>Original CSV: 7.6 GB</li><li>Compressed Parquet: 0.42 GB</li><li>Size Reduction: 94.5% 🎉</li></ul><h3>Performance Metrics:</h3><ul><li>Total Rows: 14,607,336</li><li>Total Columns: 91</li><li>Conversion Time: ~10 minutes</li><li>Search Speed: &lt;2 seconds</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5dIlVp-EBWscmxeVb8XRA.png" /></figure><h3>🏗️ Ideas for Taking It Further</h3><h3>1. Enterprise File Structure</h3><pre>/data/<br>├── raw/                 # Raw CSV files<br>├── processed/          <br>│   ├── 2023/<br>│   │   ├── 01/         # Monthly partitions<br>│   │   │   ├── part_001.parquet.zstd<br>│   │   │   ├── part_002.parquet.zstd<br>│   │   │   └── ...<br>│   │   └── 02/<br>│   └── 2024/<br>├── indexes/<br>│   ├── metadata.sqlite # Schema and file info<br>│   └── search_cache.db # Search cache<br>└── backups/            # Backups</pre><h3>2. Analytical Queries with DuckDB</h3><pre>import duckdb<br>def setup_duckdb(parquet_path):<br>    conn = duckdb.connect()<br>    conn.execute(f&quot;&quot;&quot;<br>        CREATE VIEW payments AS <br>        SELECT * FROM read_parquet(&#39;{parquet_path}&#39;)<br>    &quot;&quot;&quot;)<br>    return conn<br>def advanced_queries(conn):<br>    # Top 10 payments by state<br>    result = conn.execute(&quot;&quot;&quot;<br>        SELECT Recipient_State, <br>               COUNT(*) as payment_count,<br>               SUM(CAST(Total_Amount_of_Payment_USDollars AS DOUBLE)) as total<br>        FROM payments <br>        GROUP BY Recipient_State <br>        ORDER BY total DESC <br>        LIMIT 10<br>    &quot;&quot;&quot;).fetchdf()<br>    <br>    return result</pre><h3>3. Metadata Indexing with SQLite</h3><pre>import sqlite3<br>def create_metadata_index(parquet_files):<br>    conn = sqlite3.connect(&quot;indexes/metadata.sqlite&quot;)<br>    <br>    conn.execute(&#39;&#39;&#39;<br>        CREATE TABLE IF NOT EXISTS files (<br>            path TEXT PRIMARY KEY,<br>            rows INTEGER,<br>            size_mb REAL,<br>            created_date TEXT,<br>            min_date TEXT,<br>            max_date TEXT<br>        )<br>    &#39;&#39;&#39;)<br>    <br>    for file_path in parquet_files:<br>        df = pd.read_parquet(file_path)<br>        <br>        conn.execute(&#39;&#39;&#39;<br>            INSERT OR REPLACE INTO files <br>            VALUES (?, ?, ?, datetime(&#39;now&#39;), ?, ?)<br>        &#39;&#39;&#39;, (<br>            str(file_path),<br>            len(df),<br>            file_path.stat().st_size / (1024*1024),<br>            df[&#39;Date_of_Payment&#39;].min(),<br>            df[&#39;Date_of_Payment&#39;].max()<br>        ))<br>    <br>    conn.close()</pre><h3>💡 Real-World Impact</h3><h3>Before This Solution:</h3><ul><li>❌ Memory errors with large datasets</li><li>❌ Long loading times</li><li>❌ Storage space issues</li><li>❌ Complex data access</li></ul><h3>After Implementation:</h3><ul><li>✅ Chunked reading instead of one huge read</li><li>✅ 94.5% storage savings</li><li>✅ Faster column-based queries</li><li>✅ A clear path to DuckDB-based analytics</li></ul><h3>🎯 Key Takeaways</h3><p>This solution demonstrates:</p><ol><li>Chunked Processing: Reading in chunks avoids loading the whole CSV at once. For files larger than RAM, keep the write step streaming too (see the update below).</li><li>Smart Compression: ZSTD compression achieves 94.5% size reduction</li><li>Type Consistency: dtype=str keeps chunk schemas identical, at the cost of casting types later</li><li>Memory Management: Freeing each chunk keeps peak memory lower</li><li>Query Speed: Columnar Parquet plus DuckDB makes aggregations fast</li></ol><h3>🚀 Scaling Further</h3><h3>For Petabyte-Scale Data:</h3><ul><li>Compression ratios vary by dataset, so measure on your own data before planning storage</li><li>Distributed processing with Dask or Spark</li><li>Cloud storage integration (S3, GCS, Azure)</li><li>Columnar analytics with BigQuery or Snowflake</li></ul><h3>Performance Optimizations:</h3><ul><li>Partitioning by date/region for faster queries</li><li>Predicate pushdown to reduce data scanning</li><li>Caching frequently accessed data</li><li>Indexing on commonly queried columns</li></ul><h3>🛠️ Getting Started</h3><ol><li>Install dependencies:</li></ol><pre>pip install pandas pyarrow</pre><ol><li>Run the conversion:</li></ol><pre>python main.py</pre><ol><li>Start searching:</li></ol><pre>python search_parquet.py</pre><h3>🔗 Resources &amp; Next Steps</h3><ul><li>GitHub Repository: <a href="https://github.com/yldrykuru/big-csv-processor">Click</a></li></ul><h3>🎉 Conclusion</h3><p>Chunked reading plus Parquet turned an unwieldy 7.6GB CSV into a 0.42GB file that DuckDB can query in seconds. If your data is larger than your RAM, switch the final step to a streaming ParquetWriter as shown in the update below.</p><p>Update (Nov 2026): The script above writes small Parquet chunks, then reads them all back and concatenates them in memory, so the final step still needs the whole dataset to fit in RAM. For a truly streaming version, open one pyarrow.parquet.ParquetWriter and call write_table() for each chunk instead of collecting tables; the GitHub repository has the updated script.</p><p>Ready to implement this in your project? Start with the code above and adapt it to your specific needs!</p><p><em>If this article was helpful, please 👏 clap and share it with your network! Feel free to ask questions in the comments below.</em></p><p>Follow me: For more big data and Python content <a href="https://medium.com/u/dcdb0ac6f0f9">Yıldıray Kuru</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d09dc1f1bbd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gin RESTful API Project]]></title>
            <link>https://yldrykuru.medium.com/gin-restful-api-project-49be2649588a?source=rss-dcdb0ac6f0f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/49be2649588a</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[gorm]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[gin-framework]]></category>
            <category><![CDATA[restful-api]]></category>
            <dc:creator><![CDATA[Yıldıray Kuru]]></dc:creator>
            <pubDate>Sun, 11 Feb 2024 21:08:42 GMT</pubDate>
            <atom:updated>2024-02-11T21:13:38.387Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’ll focus on creating, configuring, and running a basic RESTful API using Golang. The entire project can be found on <a href="https://github.com/yldrykuru/gin-restful">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jv_321Sn840bEjU8.png" /></figure><h4>Project Structure</h4><p>We use the following file and folder structure to create and develop the project:</p><pre>- configs<br>- controllers<br>  - todo_controller.go<br>- db<br>  - db.go<br>  - migration.go<br>- interfaces<br>- middlewares<br>  - auth_middleware.go<br>  - cors_middleware.go<br>  - rate_limit_middleware.go<br>- models<br>  - base.go<br>  - todo.go<br>- repositories<br>  - abstract_repository.go<br>  - todo_repository.go<br>- routes<br>  - auth.go<br>  - routes.go<br>  - todos.go<br>- services<br>  - abstract_service.go<br>  - todo_service.go<br>- utils<br>  - utils.go<br>- .env<br>- .env.example<br>- Dockerfile<br>- go.mod<br>- go.sum<br>- main.go</pre><p>This structure illustrates a typical organization used to logically group and maintain code for creating a sustainable Golang project.</p><h4>Key Concepts</h4><p>Gin: A Golang web framework used for creating web applications and microservices. <a href="https://github.com/gin-gonic/gin">Gin Framework</a></p><p>GORM: Used for Object Relational Mapping (ORM) in Golang, managing database operations. <a href="https://gorm.io/">GORM ORM</a></p><h4>Examining Main Files</h4><p>This file serves as the main entry point that initializes the application. It loads relevant dependencies, sets up the router, and starts the server.</p><p>main.go:</p><pre>// main.go<br>package main<br>import (<br> &quot;log&quot;<br> &quot;strconv&quot;<br> &quot;time&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br> _ &quot;github.com/joho/godotenv/autoload&quot;<br> &quot;os&quot;<br> &quot;yldrykuru/gin-restful/db&quot;<br> &quot;yldrykuru/gin-restful/middlewares&quot;<br> &quot;yldrykuru/gin-restful/routes&quot;<br>)<br>func main() {<br> // Set the Gin operating mode based on the ENV value<br> setGinMode()<br> // Create a Gin router<br> engine := setupRouter()<br> // Perform database migration<br> db.AutoMigrate()<br> // Start the server<br> port := os.Getenv(&quot;GIN_PORT&quot;) // GIN_PORT can be used instead of PORT<br> if port == &quot;&quot; {<br>  port = &quot;8080&quot; // Default port<br> }<br> // Start the server on the specified port<br> err := engine.Run(&quot;:&quot; + port)<br> if err != nil {<br>  // Log a fatal error if the server fails to start<br>  log.Fatalf(&quot;Failed to start the server: %s&quot;, err)<br> }<br>}<br>// setupRouter configures the Gin router and sets up middleware.<br>func setupRouter() *gin.Engine {<br> // Create a new Gin engine<br> engine := gin.New()<br> engine.SetTrustedProxies([]string{&quot;127.0.0.1&quot;})<br> // Add middleware to the engine<br> engine.Use(gin.Logger(), gin.Recovery())<br> engine.Use(middlewares.CorsMiddleware())<br> // Convert RATE_LIMIT to an integer<br> rateLimit, err := strconv.Atoi(os.Getenv(&quot;RATE_LIMIT&quot;))<br> if err != nil {<br>  rateLimit = 100 // Default rate limit<br> }<br> engine.Use(middlewares.RateLimitMiddleware(rateLimit, time.Second))<br> // Configure routes<br> api := engine.Group(&quot;/api/v1&quot;)<br> routes.SetupRoutes(api)<br> return engine<br>}<br>// setGinMode sets the Gin operating mode based on the ENV value.<br>func setGinMode() {<br> // Check the value obtained from ENV<br> ginMode := os.Getenv(&quot;GIN_MODE&quot;)<br> mode := gin.ReleaseMode<br> if ginMode == &quot;&quot; || ginMode == &quot;debug&quot; {<br>  // Use DebugMode as the default if not specified in ENV<br>  mode = gin.DebugMode<br> }<br> // Set the Gin operating mode<br> gin.SetMode(mode)<br>}</pre><h4>Database Initialization (db Package)</h4><p>The db.go file initializes the connection to the MySQL database using GORM. It reads database-related environment variables (DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_NAME) from the .env file. If the connection fails, it logs a fatal error.</p><pre>// db/db.go<br>package db<br>import (<br> &quot;os&quot;<br> &quot;gorm.io/driver/mysql&quot;<br> &quot;gorm.io/gorm&quot;<br>)<br>// DB is the global variable for the Gorm database connection.<br>var DB *gorm.DB<br>// init function sets up the database connection when the package is initialized.<br>func init() {<br> // Create a DSN (Data Source Name) for the MySQL connection.<br> dsn := os.Getenv(&quot;DB_USER&quot;) + &quot;:&quot; + os.Getenv(&quot;DB_PASSWORD&quot;) +<br>  &quot;@tcp(&quot; + os.Getenv(&quot;DB_HOST&quot;) + &quot;:&quot; + os.Getenv(&quot;DB_PORT&quot;) + &quot;)/&quot; +<br>  os.Getenv(&quot;DB_NAME&quot;) + &quot;?parseTime=true&quot;<br> // Open a Gorm database connection.<br> db, err := gorm.Open(mysql.Open(dsn), &amp;gorm.Config{})<br> if err != nil {<br>  panic(&quot;Database connection failed: &quot; + err.Error())<br> }<br> // Set the global DB variable.<br> DB = db<br>}</pre><p>The migration.go file in the same package is responsible for auto-migrating the database schema. It uses GORM&#39;s AutoMigrate function to ensure that the Todo model&#39;s structure is reflected in the database.</p><pre>// db/migration.go<br>package db<br>import (<br> &quot;yldrykuru/gin-restful/models&quot;<br>)<br>// AutoMigrate function performs automatic database migration for defined models.<br>func AutoMigrate() {<br> // AutoMigrate function automatically creates or updates database tables<br> // based on the provided model structs.<br> DB.AutoMigrate(&amp;models.Todo{})<br> // If you want to add more models, you can include them here.<br>}</pre><h4>Middleware Functions (middlewares Package)</h4><p>The auth_middleware.go file contains a middleware function for authentication. Currently, it only responds with an &quot;Unauthorized&quot; JSON message, but you can extend it to handle actual authentication logic.</p><pre>// middlewares/auth_middleware.go<br>package middlewares<br>import (<br> &quot;github.com/gin-gonic/gin&quot;<br>)<br>// AuthMiddleware is a Gin middleware function for authentication.<br>func AuthMiddleware() gin.HandlerFunc {<br> return func(c *gin.Context) {<br>  // If authentication logic is implemented, it can be added here.<br>  // If authentication fails, it&#39;s common to respond with an Unauthorized error.<br>  // c.JSON(http.StatusUnauthorized, gin.H{&quot;error&quot;: &quot;Unauthorized&quot;})<br>  // If needed, further processing of the middleware chain can be implemented here.<br>  // Continue to the next middleware in the chain.<br>  c.Next()<br> }<br>}</pre><p>The cors_middleware.go file sets up Cross-Origin Resource Sharing (CORS) headers to allow requests from any origin. Adjust the configuration based on your application&#39;s security requirements.</p><pre>package middlewares<br>import (<br> &quot;github.com/gin-contrib/cors&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br>)<br>// CorsMiddleware is a Gin middleware function for handling Cross-Origin Resource Sharing (CORS).<br>func CorsMiddleware() gin.HandlerFunc {<br> // Create a new CORS configuration with default settings.<br> config := cors.DefaultConfig()<br> // Allow requests from any origin. Limiting origins is recommended for security reasons.<br> config.AllowOrigins = []string{&quot;*&quot;}<br> // Specify allowed HTTP methods.<br> config.AllowMethods = []string{&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;, &quot;OPTIONS&quot;}<br> // Specify allowed HTTP headers.<br> config.AllowHeaders = []string{&quot;Origin&quot;, &quot;Content-Type&quot;, &quot;Accept&quot;, &quot;Authorization&quot;}<br> // Create and return a new CORS middleware instance with the configured settings.<br> return cors.New(config)<br>}</pre><p>The rate_limit_middleware.go file could potentially handle rate limiting, but it appears to be incomplete in your provided code. You can implement rate limiting logic based on your project requirements.</p><h4>Models (models Package)</h4><p>The base.go file defines a BaseModel struct that includes common fields like ID, CreatedAt, UpdatedAt, and DeletedAt. This struct is embedded in other models to avoid redundant field definitions.</p><pre>// models/todo.go<br>package models<br>import (<br> &quot;time&quot;<br> &quot;gorm.io/gorm&quot;<br>)<br>// BaseModel represents the basic structure for database models.<br>type BaseModel struct {<br> ID        uint           `gorm:&quot;primaryKey&quot; json:&quot;id&quot;`<br> CreatedAt time.Time      `json:&quot;created_at&quot;`<br> UpdatedAt time.Time      `json:&quot;updated_at&quot;`<br> DeletedAt gorm.DeletedAt `gorm:&quot;index&quot; json:&quot;-&quot;`<br>}</pre><p>The todo.go file defines the Todo model, which embeds the BaseModel. It includes fields such as Title and Status. Validation is performed using struct tags.</p><h4>Repository (repositories Package)</h4><p>The todo_repository.go file in the repositories package contains functions for interacting with the database regarding todo items.</p><pre>// repositories/todo_repository.go<br>package repositories<br>import (<br> &quot;yldrykuru/gin-restful/models&quot;<br>)<br>// TodoRepository defines the repository for managing Todo models in the database.<br>type TodoRepository struct{}<br>// GetTodos retrieves a list of todos from the database with pagination.<br>// It takes &#39;page&#39; and &#39;pageSize&#39; parameters to specify the page number and<br>// the number of todos per page. The result is a slice of todos and an error.<br>// If successful, the function returns the requested todos, otherwise an error.<br>func (r *TodoRepository) GetTodos(page, pageSize int) ([]models.Todo, error) {<br> // Slice to store the retrieved todos<br> var todos []models.Todo<br> // Perform database query with pagination using Offset and Limit<br> result := database.Offset((page - 1) * pageSize).Limit(pageSize).Find(&amp;todos)<br> if result.Error != nil {<br>  // Return an error if the database query encounters an issue<br>  return nil, result.Error<br> }<br> // Return the retrieved todos and no error in case of success<br> return todos, nil<br>}<br>// GetTodoByID retrieves a todo from the database based on its ID.<br>func (r *TodoRepository) GetTodoByID(id uint) (*models.Todo, error) {<br> var todo models.Todo<br> // Find a todo by its ID from the database.<br> result := database.First(&amp;todo, id)<br> if result.Error != nil {<br>  // Return an error if there is an issue fetching the todo.<br>  return nil, result.Error<br> }<br> // Return the retrieved todo.<br> return &amp;todo, nil<br>}</pre><h4>Routes (routes Package)</h4><p>The auth.go and todos.go files in the routes package define routes for authentication-related and todo-related functionalities, respectively.</p><pre>package routes<br>import (<br> &quot;yldrykuru/gin-restful/controllers&quot;<br> &quot;yldrykuru/gin-restful/middlewares&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br>)<br>// authRoutes defines authentication-related routes under a given RouterGroup.<br>func authRoutes(engine *gin.RouterGroup) {<br> // Create a new RouterGroup for authentication routes.<br> auth := engine.Group(&quot;/auth&quot;)<br> // Apply the AuthMiddleware to all routes under the /auth group.<br> auth.Use(middlewares.AuthMiddleware())<br> // Define a route to handle GET requests at /auth/.<br> // This route is protected by the AuthMiddleware.<br> auth.GET(&quot;/&quot;, controllers.GetTodos)<br>}</pre><pre>package routes<br>import (<br> &quot;github.com/gin-gonic/gin&quot;<br>)<br>// SetupRoutes configures various route groups within the specified RouterGroup.<br>func SetupRoutes(engine *gin.RouterGroup) {<br> // Configure routes related to todos.<br> todosRoutes(engine)<br> // Configure authentication-related routes.<br> authRoutes(engine)<br>}</pre><h4>Controllers (controllers Package)</h4><p>The todo_controller.go file in the controllers package contains functions to handle HTTP requests related to todo items.</p><pre>// controllers/todo_controller.go<br>package controllers<br>import (<br> &quot;net/http&quot;<br> &quot;strconv&quot;<br> &quot;yldrykuru/gin-restful/models&quot;<br> &quot;yldrykuru/gin-restful/repositories&quot;<br> &quot;yldrykuru/gin-restful/services&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br>)<br>// GetTodos is a controller function to handle the retrieval of paginated todos.<br>func GetTodos(c *gin.Context) {<br> // Initialize TodoRepository<br> todoRepository := repositories.TodoRepository{}<br> // Retrieve page and pageSize from query parameters with default values<br> page, _ := strconv.Atoi(c.Query(&quot;page&quot;))<br> if page &lt;= 0 {<br>  page = 1<br> }<br> pageSize, _ := strconv.Atoi(c.Query(&quot;pageSize&quot;))<br> if pageSize &lt;= 0 {<br>  pageSize = 10 // Default page size<br> }<br> // Retrieve paginated todos from the repository<br> todos, err := todoRepository.GetTodos(page, pageSize)<br> if err != nil {<br>  // If there is an error fetching todos, respond with an Internal Server Error<br>  c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: &quot;Failed to fetch todos&quot;})<br>  return<br> }<br> // Respond with the retrieved paginated todos<br> c.JSON(http.StatusOK, gin.H{&quot;todos&quot;: todos})<br>}<br>// GetTodo function to retrieve a specific todo by ID<br>func GetTodo(c *gin.Context) {<br> idParam := c.Param(&quot;id&quot;)<br> id, err := strconv.Atoi(idParam)<br> if err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: &quot;Invalid todo ID&quot;})<br>  return<br> }<br> todoRepository := repositories.TodoRepository{}<br> todo, err := todoRepository.GetTodoByID(uint(id))<br> if err != nil {<br>  c.JSON(http.StatusNotFound, gin.H{&quot;error&quot;: &quot;Todo not found&quot;})<br>  return<br> }<br> c.JSON(http.StatusOK, gin.H{&quot;todo&quot;: todo})<br>}<br>// AddTodo function to add a new todo<br>func AddTodo(c *gin.Context) {<br> var todo models.Todo<br> // Bind JSON data<br> if err := c.ShouldBindJSON(&amp;todo); err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>  return<br> }<br> // Validate the model<br> if err := todo.Validate(); err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>  return<br> }<br> // Add todo to the database<br> todoService := services.TodoService{}<br> data, err := todoService.AddTodo(&amp;todo)<br> if err != nil {<br>  c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: &quot;Failed to add todo to the database&quot;})<br>  return<br> }<br> c.JSON(http.StatusCreated, gin.H{&quot;message&quot;: &quot;Todo created successfully&quot;, &quot;todo&quot;: data})<br>}<br>// EditTodo function to edit an existing todo<br>func EditTodo(c *gin.Context) {<br> // Get todo ID from the request<br> todoID, err := strconv.ParseUint(c.Param(&quot;id&quot;), 10, 64)<br> if err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: &quot;Invalid todo ID&quot;})<br>  return<br> }<br> var updatedTodo models.Todo<br> // Bind JSON data<br> if err := c.ShouldBindJSON(&amp;updatedTodo); err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>  return<br> }<br> // Validate the model<br> if err := updatedTodo.Validate(); err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>  return<br> }<br> // Edit the todo in the database<br> todoService := services.TodoService{}<br> data, err := todoService.EditTodo(uint(todoID), &amp;updatedTodo)<br> if err != nil {<br>  c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: &quot;Failed to edit todo in the database&quot;})<br>  return<br> }<br> c.JSON(http.StatusOK, gin.H{&quot;message&quot;: &quot;Todo updated successfully&quot;, &quot;todo&quot;: data})<br>}<br>// DeleteTodo function to delete an existing todo<br>func DeleteTodo(c *gin.Context) {<br> // Get todo ID from the request<br> todoID, err := strconv.ParseUint(c.Param(&quot;id&quot;), 10, 64)<br> if err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: &quot;Invalid todo ID&quot;})<br>  return<br> }<br> // Delete the todo from the database<br> todoService := services.TodoService{}<br> err = todoService.DeleteTodo(uint(todoID))<br> if err != nil {<br>  c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: &quot;Failed to delete todo from the database&quot;})<br>  return<br> }<br> c.JSON(http.StatusOK, gin.H{&quot;message&quot;: &quot;Todo deleted successfully&quot;})<br>}</pre><h4>Services (services Package)</h4><p>The todo_service.go file in the services package contains business logic for todo items, such as adding, editing, and deleting them.</p><pre>// services/todo_service.go<br>package services<br>import (<br> &quot;yldrykuru/gin-restful/models&quot;<br> &quot;yldrykuru/gin-restful/repositories&quot;<br>)<br>// TodoService defines the service layer for managing Todo entities.<br>type TodoService struct {<br> // Additional fields can be added if needed.<br>}<br>// AddTodo defines the function to add a new Todo to the database.<br>func (s *TodoService) AddTodo(todo *models.Todo) (*models.Todo, error) {<br> // Create a new Todo instance with the provided data.<br> newTodo := models.Todo{<br>  Title:  todo.Title,<br>  Status: todo.Status,<br> }<br> // Add the new Todo to the database.<br> database.Create(&amp;newTodo)<br> // No need to perform error checking since the Create function doesn&#39;t return an error.<br> return &amp;newTodo, nil<br>}<br>// EditTodo defines the function to edit an existing Todo in the database.<br>func (s *TodoService) EditTodo(todoID uint, todo *models.Todo) (*models.Todo, error) {<br> // Retrieve the existing Todo from the database using its ID.<br> todoRepository := repositories.TodoRepository{}<br> existingTodo, err := todoRepository.GetTodoByID(todoID)<br> if err != nil {<br>  return nil, err<br> }<br> // Update the existing Todo with the provided data.<br> existingTodo.Title = todo.Title<br> existingTodo.Status = todo.Status<br> // Save the updated Todo to the database.<br> database.Save(existingTodo)<br> return existingTodo, nil<br>}<br>// DeleteTodo defines the function to delete an existing Todo from the database.<br>func (s *TodoService) DeleteTodo(todoID uint) error {<br> // Retrieve the existing Todo from the database using its ID.<br> todoRepository := repositories.TodoRepository{}<br> existingTodo, err := todoRepository.GetTodoByID(todoID)<br> if err != nil {<br>  return err<br> }<br> // Delete the Todo from the database.<br> database.Delete(existingTodo)<br> return nil<br>}</pre><h4>Dockerfile</h4><p>The Dockerfile is used to build a Docker image for your application. It copies the project files, builds the Go application, and exposes port 8080.</p><pre># Dockerfile<br>FROM golang:latest<br>WORKDIR /app<br>COPY . .<br>RUN go build -o main .<br>EXPOSE 8080<br>CMD [&quot;./main&quot;]</pre><h4>Additional Suggestions</h4><ul><li>Documentation: Consider adding comments and documentation where necessary, especially for complex logic or non-trivial functions.</li><li>Testing: Implement unit tests to ensure the correctness of your code. You can create a tests folder to house your test files.</li><li>Error Handling: Enhance error handling throughout your application. Provide meaningful error messages and log errors appropriately.</li><li>Logging: Introduce a logging library to log relevant information, warnings, and errors. Logging is essential for debugging and monitoring.</li><li>Rate Limiting Middleware: Implement the rate_limit_middleware.go file to handle rate limiting if it&#39;s part of your project requirements.</li><li>Configuration Management: If your application’s configuration grows, consider using a dedicated configuration management library or package.</li><li>Dependency Management: Regularly update your dependencies to benefit from bug fixes, new features, and security patches.</li></ul><p>With these considerations, your Gin RESTful API project is on a solid foundation. Feel free to expand on each section based on your project’s specific needs and requirements.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49be2649588a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Real-Time Drawing Collaboration with Socket.IO and Paper.js]]></title>
            <link>https://yldrykuru.medium.com/building-a-real-time-drawing-collaboration-with-socket-io-and-paper-js-48de0eb85313?source=rss-dcdb0ac6f0f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/48de0eb85313</guid>
            <dc:creator><![CDATA[Yıldıray Kuru]]></dc:creator>
            <pubDate>Wed, 07 Feb 2024 23:16:38 GMT</pubDate>
            <atom:updated>2024-02-07T23:16:38.663Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial, we’ll explore how to create a real-time drawing collaboration project using Socket.IO and Paper.js. We’ll build a simple drawing and guessing game where users can collaborate in real-time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7v-gWKnI3egptendeNaUKw.png" /></figure><h3>Prerequisites</h3><p>Before we start, ensure you have the following installed:</p><ul><li>Node.js: If not installed, you can download it <a href="https://nodejs.org/">here</a>.</li></ul><h3>Starting the Server</h3><ul><li>Creating the Server File (server.js):</li></ul><pre>const express = require(&#39;express&#39;);<br>const http = require(&#39;http&#39;);<br>const socketIO = require(&#39;socket.io&#39;);<br>const path = require(&#39;path&#39;);<br><br>const app = express();<br>const server = http.createServer(app);<br>const io = socketIO(server);<br><br>const PORT = process.env.PORT || 3000;<br><br>// Serve static files from the &#39;public&#39; folder<br>app.use(express.static(path.join(__dirname, &#39;public&#39;)));<br><br>// Handle the root URL by sending the &#39;index.html&#39; file from the &#39;public&#39; folder<br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.sendFile(path.join(__dirname, &#39;public&#39;, &#39;index.html&#39;));<br>});<br><br>// Handle connections with Socket.IO<br>io.on(&#39;connection&#39;, (socket) =&gt; {<br>  console.log(&#39;A user connected&#39;);<br><br>  // Listen for the &#39;draw&#39; event<br>  socket.on(&#39;draw&#39;, (data) =&gt; {<br>    // Receive drawing data and broadcast it to other clients<br>    socket.broadcast.emit(&#39;draw&#39;, data);<br>  });<br><br>  // Handle disconnections<br>  socket.on(&#39;disconnect&#39;, () =&gt; {<br>    console.log(&#39;A user disconnected&#39;);<br>  });<br>});<br><br>// Start the server and listen on the specified port<br>server.listen(PORT, () =&gt; {<br>  console.log(`Server listening on port ${PORT}`);<br>});</pre><h3>Setting Up the Client</h3><ul><li>Creating the Drawing Canvas (index.html):</li></ul><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br><br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>  &lt;title&gt;Realtime Drawing&lt;/title&gt;<br>  &lt;style&gt;<br>    /* Add styles to make the entire page fullscreen */<br>    body,<br>    html {<br>      margin: 0;<br>      padding: 0;<br>      width: 100%;<br>      height: 100%;<br>      overflow: hidden;<br>    }<br><br>    canvas {<br>      display: block;<br>    }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>  &lt;!-- Create a drawing area by adding the canvas element --&gt;<br>  &lt;canvas id=&quot;myCanvas&quot; style=&quot;border: 1px solid #000;&quot;&gt;&lt;/canvas&gt;<br><br>  &lt;!-- Include Socket.IO and Paper.js libraries for client-side scripting --&gt;<br>  &lt;script src=&quot;/socket.io/socket.io.js&quot;&gt;&lt;/script&gt;<br>  &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.17/paper-full.min.js&quot;&gt;&lt;/script&gt;<br><br>  &lt;!-- Include the client-side script file containing game controls --&gt;<br>  &lt;script src=&quot;app.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><ul><li>Handling Drawing on the Canvas (app.js):</li></ul><pre>// Connect to the server with Socket.IO<br>const socket = io();<br><br>// Select the Canvas element<br>const canvas = document.getElementById(&#39;myCanvas&#39;);<br>const context = canvas.getContext(&#39;2d&#39;);<br><br>canvas.width = window.innerWidth;<br>canvas.height = window.innerHeight;<br><br>let drawing = false; // Drawing mode: true if drawing, false if not<br>let prevX = 0; // Previous mouse position X<br>let prevY = 0; // Previous mouse position Y<br><br>// When drawing starts<br>canvas.addEventListener(&#39;mousedown&#39;, (e) =&gt; {<br>    drawing = true; // Start drawing mode<br>    [prevX, prevY] = [e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop]; // Set the starting point<br>    context.beginPath(); // Start a new drawing path<br>    context.moveTo(prevX, prevY); // Move to the starting point<br>});<br><br>// When drawing continues<br>canvas.addEventListener(&#39;mousemove&#39;, (e) =&gt; {<br>    if (!drawing) return; // Exit if not in drawing mode<br><br>    const currentX = e.clientX - canvas.offsetLeft; // Current mouse position X<br>    const currentY = e.clientY - canvas.offsetTop; // Current mouse position Y<br><br>    // Draw a smooth line between the two points<br>    context.lineJoin = &#39;round&#39;; // Round line joins<br>    context.lineCap = &#39;round&#39;; // Round line ends<br>    context.lineWidth = 2; // Line thickness<br>    context.lineTo(currentX, currentY); // Draw up to the current position<br>    context.stroke(); // Apply the drawing<br><br>    // Emit more precise drawing information to the server<br>    socket.emit(&#39;draw&#39;, {<br>        x1: prevX,<br>        y1: prevY,<br>        x2: currentX,<br>        y2: currentY,<br>    });<br><br>    [prevX, prevY] = [currentX, currentY]; // Update the previous position to the current position<br>});<br><br>// When drawing ends<br>canvas.addEventListener(&#39;mouseup&#39;, () =&gt; {<br>    drawing = false; // End drawing mode<br>    context.closePath(); // Close the drawing path<br>});<br><br>// Receive drawing information from the server<br>socket.on(&#39;draw&#39;, (data) =&gt; {<br>    // Draw based on the received drawing information<br>    context.lineJoin = &#39;round&#39;;<br>    context.lineCap = &#39;round&#39;;<br>    context.lineWidth = 2;<br>    context.beginPath();<br>    context.moveTo(data.x1, data.y1);<br>    context.lineTo(data.x2, data.y2);<br>    context.stroke();<br>});</pre><h3>Conclusion</h3><p>Congratulations! You’ve successfully built a real-time drawing collaboration project. To explore the complete source code and experiment with the project, visit the GitHub repository:</p><p><a href="https://github.com/yldrykuru/realtime-drawing">Real-Time Drawing Repository</a></p><p>Feel free to fork, contribute, or use it as a foundation for your own real-time collaboration projects.</p><h3>Next Steps and Enhancements</h3><h4>Here are some suggestions for enhancing the project:</h4><ol><li>Color Options: Allow users to choose different colors for their drawings, enhancing the overall drawing experience.</li><li>Save and Share Drawings: Implement a feature to save and share drawings, providing users with the ability to showcase their collaborative creations.</li></ol><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48de0eb85313" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Chat Application with Socket.IO: A Simple Guide]]></title>
            <link>https://yldrykuru.medium.com/real-time-chat-application-with-socket-io-a-simple-guide-e8b664640887?source=rss-dcdb0ac6f0f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8b664640887</guid>
            <dc:creator><![CDATA[Yıldıray Kuru]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 23:34:45 GMT</pubDate>
            <atom:updated>2024-02-07T23:37:32.222Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XSSVNAs6ZnhAr8HPPzc63g.jpeg" /></figure><h3>Introduction</h3><p>In this tutorial, we’ll explore how to create a real-time chat application using Socket.IO and Express. Real-time communication is essential for many modern web applications, and Socket.IO provides an efficient way to achieve it. We’ll build a simple chat interface where users can send and receive messages instantly.</p><h3>Setting Up the Project:</h3><ol><li>Install Node.js if you haven’t already.</li><li>Create a new project folder and navigate to it in the terminal.</li><li>Run npm init to initialize a new Node.js project and follow the prompts.</li><li>Install the required packages: npm install express http socket.io</li></ol><h4>Server-Side Implementation:</h4><pre>// Import required modules<br>const express = require(&#39;express&#39;);<br>const http = require(&#39;http&#39;);<br>const socketIO = require(&#39;socket.io&#39;);<br><br>// Create an Express application<br>const app = express();<br><br>// Create an HTTP server using the Express application<br>const server = http.createServer(app);<br><br>// Create a Socket.IO instance by passing the HTTP server<br>const io = socketIO(server);<br><br>// Serve static files from the &#39;public&#39; directory<br>app.use(express.static(&#39;public&#39;));<br><br>// Define a route to serve the index.html file<br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>    res.sendFile(__dirname + &#39;/public/index.html&#39;);<br>});<br><br>// Handle socket connections<br>io.on(&#39;connection&#39;, (socket) =&gt; {<br>    // Send an example message to the connecting client<br>    socket.emit(&#39;clientMessage&#39;, { value: &quot;Connection successful. Welcome to the server!&quot; });<br><br>    // Log the message sent by the client to the server console<br>    socket.on(&#39;clientMessage&#39;, (data) =&gt; {<br>        console.log(&#39;Client message:&#39;, data.value);<br><br>        // Broadcast the message from the server to all connected clients<br>        io.emit(&#39;serverMessage&#39;, { value: data.value });<br>    });<br>});<br><br>// Define the port number for the server to listen on<br>const PORT = process.env.PORT || 3000;<br><br>// Start the server and listen on the specified port<br>server.listen(PORT, () =&gt; {<br>    console.log(`Server is listening on port ${PORT}`);<br>});</pre><h4>Client-Side Implementation:</h4><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br><br>&lt;head&gt;<br>    &lt;!-- Set the title and define metadata --&gt;<br>    &lt;title&gt;Socket.IO Example&lt;/title&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br><br>    &lt;!-- Include Bootstrap CSS and jQuery --&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css&quot;&gt;<br>    &lt;script src=&quot;https://code.jquery.com/jquery-3.6.4.min.js&quot;&gt;&lt;/script&gt;<br><br>    &lt;!-- Include Socket.IO library --&gt;<br>    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.4/socket.io.js&quot; integrity=&quot;sha512-tE1z+95+lMCGwy+9PnKgUSIeHhvioC9lMlI7rLWU0Ps3XTdjRygLcy4mLuL0JAoK4TLdQEyP0yOl/9dMOqpH/Q==&quot; crossorigin=&quot;anonymous&quot; referrerpolicy=&quot;no-referrer&quot;&gt;&lt;/script&gt;<br><br>    &lt;!-- Add custom styles --&gt;<br>    &lt;style&gt;<br>        /* Your CSS styles go here */<br>        body {<br>            background-color: #f8f9fa;<br>        }<br><br>        #chat-container {<br>            max-width: 500px;<br>            margin: 50px auto;<br>            padding: 20px;<br>            border: 1px solid #ced4da;<br>            border-radius: 5px;<br>            background-color: #fff;<br>        }<br><br>        #messages {<br>            margin-top: 20px;<br>            border-top: 1px solid #ced4da;<br>            padding-top: 10px;<br>        }<br><br>        #messages p {<br>            margin: 5px 0;<br>            padding: 8px;<br>            background-color: #f1f1f1;<br>            border-radius: 5px;<br>        }<br><br>        label {<br>            margin-top: 10px;<br>            font-weight: bold;<br>        }<br><br>        input {<br>            margin-bottom: 10px;<br>        }<br><br>        button {<br>            display: block;<br>            margin-top: 10px;<br>            padding: 8px 20px;<br>            background-color: #007bff;<br>            color: #fff;<br>            border: none;<br>            border-radius: 5px;<br>            cursor: pointer;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>    &lt;!-- Create a container for the chat interface --&gt;<br>    &lt;div id=&quot;chat-container&quot;&gt;<br>        &lt;!-- Input field and button for sending messages --&gt;<br>        &lt;label for=&quot;message&quot;&gt;Message:&lt;/label&gt;<br>        &lt;input id=&quot;message&quot; type=&quot;text&quot; class=&quot;form-control&quot;&gt;<br>        &lt;button id=&quot;send&quot; class=&quot;btn btn-primary&quot;&gt;Send Message&lt;/button&gt;<br><br>        &lt;!-- Container for displaying messages --&gt;<br>        &lt;div id=&quot;messages&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br><br>    &lt;!-- JavaScript code for handling socket communication --&gt;<br>    &lt;script&gt;<br>        // Use jQuery to wait for the document to be ready<br>        $(document).ready(function () {<br>            // Connect to the Socket.IO server<br>            var socket = io.connect(&quot;http://localhost:3000&quot;);<br><br>            // Listen for server messages and display them on the screen<br>            socket.on(&#39;serverMessage&#39;, function (data) {<br>                console.log(&#39;Server message:&#39;, data.value);<br>                $(&quot;#messages&quot;).append(&quot;&lt;p&gt;&quot; + data.value + &quot;&lt;/p&gt;&quot;);<br>            });<br><br>            // Handle button click to send messages to the server<br>            $(&quot;#send&quot;).click(function () {<br>                var message = $(&#39;#message&#39;).val();<br>                socket.emit(&#39;clientMessage&#39;, { value: message });<br><br>                // Clear the input field after sending<br>                $(&#39;#message&#39;).val(&#39;&#39;);<br>            });<br>        });<br>    &lt;/script&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sI3KgvX7Z_vWqG4ZJI5eMA.jpeg" /></figure><h4>Conclusion:</h4><p>Congratulations! You’ve successfully built a real-time chat application using Socket.IO and Express. This project provides a foundation for more advanced features and can be extended for different use cases. Experiment with additional functionalities like private messaging, user authentication, or message persistence to enhance the application further.</p><p>visit the GitHub repository: <a href="https://github.com/yldrykuru/simple-socket-chat">Real-Time Chat Repository</a></p><h4>Further Enhancements:</h4><ul><li>Implement user authentication for a secure chat environment.</li><li>Store chat history in a database for persistence.</li><li>Add multimedia support for sharing images or files.</li></ul><p>Feel free to customize and expand upon this project to meet your specific requirements.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8b664640887" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>