<?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 goodspeed on Medium]]></title>
        <description><![CDATA[Stories by goodspeed on Medium]]></description>
        <link>https://medium.com/@amazing_gs?source=rss-d3e03fee4ef7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*d_wLN92w5umI6TX7.gif</url>
            <title>Stories by goodspeed on Medium</title>
            <link>https://medium.com/@amazing_gs?source=rss-d3e03fee4ef7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:07:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amazing_gs/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[Top 5 Chrome Extensions for Meta-Tag Retrieval]]></title>
            <link>https://medium.com/@amazing_gs/top-5-chrome-extensions-for-meta-tag-retrieval-e476c34512f7?source=rss-d3e03fee4ef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e476c34512f7</guid>
            <category><![CDATA[chrome-extension]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[free]]></category>
            <category><![CDATA[seo]]></category>
            <dc:creator><![CDATA[goodspeed]]></dc:creator>
            <pubDate>Sun, 01 Dec 2024 08:16:14 GMT</pubDate>
            <atom:updated>2024-12-01T08:16:14.463Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s digital landscape, understanding the meta tags of a webpage is crucial for SEO and content optimization. Whether you’re a content creator, SEO expert, or developer, having the ability to quickly fetch and manage meta tag information is an invaluable skill. In this article, we’ll explore five of the best Chrome extensions that make retrieving meta tags a breeze.</p><h3>1. Meta Tag Fetcher</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MnMIHvLPY_7z5RGP0E3fEg.png" /><figcaption>meta tag fetcher</figcaption></figure><p>link: <a href="https://chromewebstore.google.com/detail/meta-tag-fetcher/elofmphoehdbhkibcelahonkmpgchkgi">chrome link</a></p><p><a href="https://chromewebstore.google.com/detail/meta-tag-fetcher/elofmphoehdbhkibcelahonkmpgchkgi"><strong>Meta Tag Fetcher</strong></a> is a robust Chrome extension designed for extracting, managing, and customizing meta tags from web pages. It supports real-time extraction of all standard meta tags, Open Graph, and Twitter Card tags. The user interface is modern and intuitive, offering both table and JSON views for easy data management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AVj4CObtFl6u55Rkj-9GUg.png" /><figcaption>json view</figcaption></figure><h3>Key Features</h3><ul><li><strong>Real-Time Extraction</strong>: Automatically fetches meta tags from the active tab.</li><li><strong>Custom Field Mapping</strong>: Allows users to map meta tag fields to custom names.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUbISU2_YgIyJqqs_9VzTg.png" /><figcaption>customs field mapping</figcaption></figure><ul><li><strong>Data Management</strong>: View data in table and JSON formats, and export history data.</li></ul><h3>Why Choose Meta Tag Fetcher?</h3><p>Compared to other extensions, Meta Tag Fetcher offers a comprehensive set of features with a user-friendly interface. Its support for multiple meta tag formats and customizable field mapping makes data management highly flexible.</p><h3>2. Meta SEO Inspector</h3><p><a href="https://chromewebstore.google.com/detail/meta-seo-inspector/ibkclpciafdglkjkcibmohobjkcfkaef"><strong>Meta SEO Inspector</strong></a> is a tool focused on SEO, helping users inspect meta tags and other SEO-related information on web pages. It provides detailed reports to assist in optimizing a page’s SEO performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3dVpns5bD6dvmMXIUm-PA.png" /><figcaption>meta seo inspector</figcaption></figure><h3>Key Features</h3><ul><li><strong>SEO Analysis</strong>: Offers detailed SEO reports, including meta tags, titles, and descriptions.</li><li><strong>Real-Time Inspection</strong>: Checks SEO information as you browse.</li></ul><h3>Why Choose Meta SEO Inspector?</h3><p>If your primary goal is to enhance your webpage’s SEO performance, Meta SEO Inspector is a great choice. It provides comprehensive SEO analysis reports to help identify and fix SEO issues.</p><h3>3. Open Graph Preview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sM37qsREJ_Ri9ZVWAf9Sbw.png" /></figure><p><a href="https://chromewebstore.google.com/detail/ograph-previewer/ggcfeakcnodgcmmllfdbmngekljbhiim"><strong>Open Graph Preview</strong></a> specializes in extracting and previewing Open Graph tags. It allows users to see how a webpage will appear on social media, aiding in optimizing social sharing.</p><h3>Key Features</h3><ul><li><strong>Open Graph Tag Extraction</strong>: Extracts Open Graph tags from web pages.</li><li><strong>Social Media Preview</strong>: View how a webpage will appear on social media platforms.</li></ul><h3>Why Choose Open Graph Preview?</h3><p>For users looking to optimize social media sharing, Open Graph Preview is an ideal choice. It provides intuitive social media previews to help enhance sharing effectiveness.</p><h3>4. Twitter Card Validator</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVjGjnpOvS11eewOWprCSw.png" /></figure><p><a href="https://chromewebstore.google.com/detail/twitter-card-validator/ehaanihobfkdbiagofmalaljnkhpajmm"><strong>Twitter Card Validator</strong></a> focuses on extracting and validating Twitter Card tags. It ensures that your webpage’s Twitter Card tags are set correctly for optimal display on Twitter.</p><h3>Key Features</h3><ul><li><strong>Twitter Card Tag Extraction</strong>: Extracts Twitter Card tags from web pages.</li><li><strong>Tag Validation</strong>: Validates the correctness of Twitter Card tags.</li></ul><h3>Why Choose Twitter Card Validator?</h3><p>If you want to optimize how your webpage appears on Twitter, Twitter Card Validator is a must-have tool. It helps ensure that Twitter Card tags are correctly set, avoiding display issues.</p><h3>5. SEO Meta in 1 Click</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*000SdN6Nh3FQbu8GUOjrZw.png" /></figure><p><a href="https://chromewebstore.google.com/detail/seo-meta-in-1-click/bjogjfinolnhfhkbipphpdlldadpnmhc"><strong>SEO Meta in 1 Click</strong></a> is a straightforward extension that helps users quickly view a webpage’s meta tags and SEO information. It offers a one-click view feature for easy access to the information you need.</p><h3>Key Features</h3><ul><li><strong>One-Click View</strong>: Quickly view meta tags and SEO information of a webpage.</li><li><strong>Simple Interface</strong>: Clean and easy-to-use interface.</li></ul><h3>Why Choose SEO Meta in 1 Click?</h3><p>For users who need to quickly check a webpage’s meta tags, SEO Meta in 1 Click is an ideal choice. Its one-click view feature significantly boosts efficiency.</p><h3>Conclusion</h3><p>Choosing the right meta tag retrieval tool depends on your specific needs. Whether you require comprehensive features or focus on a particular area, these five extensions can provide the assistance you need. We hope this article helps you find the perfect tool to enhance your workflow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e476c34512f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 40-Year Evolution of RPC: From Simple Procedure Calls to Modern Microservices]]></title>
            <link>https://medium.com/@amazing_gs/the-40-year-evolution-of-rpc-from-simple-procedure-calls-to-modern-microservices-7ac410bf5df2?source=rss-d3e03fee4ef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ac410bf5df2</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[goodspeed]]></dc:creator>
            <pubDate>Sat, 02 Nov 2024 13:17:59 GMT</pubDate>
            <atom:updated>2024-11-02T13:17:59.448Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XBlvm2ZaDGQST28MSs-QNw.png" /><figcaption>Evolution of Remote Procedure Calls</figcaption></figure><blockquote><em>“Does developer convenience really trump correctness, scalability, performance, separation of concerns, extensibility, and accidental complexity?” — Vinoski (2008)</em></blockquote><h3>Outline</h3><ul><li>RPC Basic Introduction</li><li>RPC Development History</li></ul><h3>RPC Introduction</h3><p>Remote Procedure Call (RPC) is a design paradigm that enables communication between two entities through a generic request/response mechanism over a communication channel. The definition of RPC has undergone significant changes and evolution over the past thirty years, making it a broad taxonomic term encompassing all RPC-style systems that have emerged over forty years. Through decades of development, RPC’s definition has evolved from a simple client-server design to a set of interconnected services. While initial RPC implementations were designed as tools for offloading computation to servers in distributed systems, years of evolution have built a language-agnostic application ecosystem. The RPC paradigm has become part of the driving force behind creating truly revolutionary distributed systems, spawning various communication schemes and protocols between different systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*s1FrhCUm4GeJMLuYkQm6lQ.png" /></figure><p>The simplest RPC implementation is shown in Figure 1. In this case, the client (or caller) and server (or callee) are separated by a physical network. The system’s main components are the client routine/program, client stub, server routine/program, server stub, and network routines. A stub is a small program that typically serves as a substitute (or interface) for a larger program. The client stub exposes the functionality provided by server routines to the client routine, while the server stub provides client-like programs to server routines. The client stub receives input parameters from the client program and returns results, while the server stub provides input parameters to the server program and retrieves results. The client program can only interact with the client stub, which provides the interface for the remote server.</p><p>This stub also serializes the input parameters sent from the client routine to the stub. Similarly, the server stub provides the client interface for the server routine and handles data serialization sent to the client.</p><p>When the client routine executes a remote procedure, it calls the client stub, which serializes the input parameters. This serialized data is sent to the server using OS network routines (TCP/IP). The server stub then deserializes the data and provides it to the server routine with the given parameters. The return values from the server routine are serialized again and sent back to the client through the network, where the client stub deserializes them and presents them to the client routine. This remote procedure is typically hidden from the client routine and appears as a local procedure to the client. RPC services also require a discovery service/host resolution mechanism to bootstrap communication between client and server.</p><p><strong>Complete RPC Framework</strong></p><p>In a typical RPC use case, it includes components such as service discovery, load balancing, fault tolerance, network transport, and serialization, where “RPC protocol” specifically defines how programs perform network transport and serialization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q1mgjWBA1p7fNvyF.png" /></figure><h3>The Development History of RPC</h3><h3>November 1969: Establishment of ARPAnet</h3><p>In 1969, the Advanced Research Projects Agency (ARPA) of the U.S. Department of Defense began establishing a network named ARPAnet. Initially, it had only four nodes, connecting the large computers at four universities: UCLA, UC Santa Barbara, Stanford University, and the University of Utah. One reason for selecting these four nodes was to test network compatibility between different types of hosts.</p><h3>1974: Jon Postel and Jim White Published RFC 674</h3><p>Procedure calls can be traced back to the Procedure Call Protocol Documents Version 2 (RFC 674) published by Jon Postel and Jim White in 1974. This protocol attempted to define a general method for solving communication problems between multiple compute nodes in the NSW project.</p><p>After the protocol was published, it sparked significant controversy, and in 1975, RFC 684 was published as an annotation to RFC 674.</p><h3>1975: RFC 684 Published as Commentary to RFC 674</h3><p>RFC 684 is not an independent protocol; it mainly discusses the controversies of RFC 674. The discussion can be summarized in the following points:</p><ul><li>RFC 674 believed that procedure calls should be primitive operations, operating at the operating system’s bottom layer</li><li>A primitive is an instruction for calling core-layer subroutines in the operating system. The difference from general broad instructions is that it is non-interruptible and always appears as a basic unit.</li><li>Local calls and remote calls are different; remote calls may fail and might not be recoverable after failure.</li><li>Asynchronous message passing, or explicitly declaring when synchronous waiting for message return is needed, should be a better model.</li></ul><p>From these points, concerns about this programming paradigm became an eternal topic in RPC’s 40-year history, namely:</p><ul><li>How to recover from failures or errors? Retry, throw exceptions?</li><li>Sequential operations are very difficult. For instance, in a series of synchronous requests, how to ensure failed requests are re-executed and requests remain in order?</li><li>RPC requests are synchronous models; methods wait for responses after being called, but because requests are synchronous, it becomes very difficult to prioritize high-priority requests when system load is high.</li><li>Synchronization is more oriented towards one-to-one calls and returns, rather than asynchronous characteristics of single requests and multiple returns. Moreover, low-priority, preemptible background tasks are unlikely to be implemented in procedure calls.</li></ul><blockquote><em>At this time, the protocol was still based on ARPANET, before the Internet existed, yet they were already discussing issues of inter-distributed system calls.</em></blockquote><h3>1976: RFC 707 Published</h3><blockquote><em>Due to the cost differences between remote and local calls, application programmers must use remote resources cautiously, even though the RTE will greatly simplify the mechanism for using remote resources. Like virtual memory, the procedure call model provides great convenience and powerful capabilities, while at the same time there should be reasonable vigilance against potential abuse.</em></blockquote><p>RFC 707 summarized the ideas of RFC 684 and discussed resource sharing issues with services such as TELNET and FTP, where each service provided different interfaces for interaction, requiring operators to know specific protocols for interacting with that service. In response to this issue, the authors proposed a new idea: rather than needing to know all available commands and protocols on remote computers, could we define a universal interface that accepts parameters and follows a call/response model to execute a remote procedure?</p><h3>January 1, 1983: ARPA Network Changed its Core Protocol from Network Control Program to TCP/IP</h3><p>On January 1, 1983, the ARPA network changed its core protocol from Network Control Program to TCP/IP protocol, and the seeds of the Internet began to sprout.</p><h3>1984: Paper “Implementing Remote Procedure Calls” Published</h3><p>RPC is the abbreviated form of Remote Procedure Call. Birrell and Nelson’s paper “Implementing Remote Procedure Calls” published in ACM Transactions on Computer Systems in 1984 gave RPC its classic interpretation. RPC refers to a process on computer A calling a process on another computer B, where the calling process on A is suspended while the called process on B begins execution, and when the value returns to A, A’s process continues execution. The caller can transmit information to the callee using parameters, and can later receive information through returned results. This process is transparent to developers. In the following years, RPC was considered the most suitable paradigm for building distributed operating systems.</p><blockquote><em>RPC (Remote Procedure Call) is a communication mechanism between multiple processes built on top of Socket. Unlike complex Socket communication methods, RPC’s original intention was to design a universal framework for remote communication. This framework could automatically handle complex details such as communication protocols, object serialization, and network transmission. Furthermore, it hoped that after developers used this framework, the code for calling an interface on a remote machine would “look no different” from local method calls, thus greatly reducing the development difficulty of distributed systems and enabling programmers unfamiliar with network programming to develop distributed systems relatively easily.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/0*d5R-xexmN8OqcQ8s.png" /></figure><p>This is the RPC architecture diagram from the paper, showing that user, user-stub, and one instance of RPCRuntime execute on the caller’s machine; server, server-stub, and another instance of RPCRuntime execute on the callee’s machine. When the user initiates a remote call, it actually executes a completely normal local call, which will call the corresponding program in the user-stub. The user-stub is responsible for placing the specification and parameters of the target program in one or more packages (packing) and requesting the RPCRuntime to reliably transmit these packages to the callee’s machine. Once these packages are received, the RPCRuntime on the callee’s machine delivers them to the server-stub. The server-stub unpacks them and calls the corresponding program in the server as if executing a completely normal local call.</p><p>Meanwhile, the calling process on the caller’s machine will be suspended and wait for the return of result packages. When the call in the server completes, it returns the results to the user-stub for packaging, then the result packages will be transmitted back by RPCRuntime to the suspended process on the caller’s machine (RPCRuntime is responsible for retransmission, acknowledgment, packet routing, and encryption). These packages will be unpacked by the user-stub and returned to the user. Apart from the impact of inter-machine binding or communication failures, the call appears as if the user directly called the program on the server. Indeed, if the user and server code are placed on the same machine and directly bound together (without stubs), the program would still work.</p><h3>1987: “A Critique of the Remote Procedure Call Paradigm” Published</h3><p>In 1987, Tanenbaum and Renesse published the article “A Critique of the Remote Procedure Call Paradigm,” discussing RPC model’s conceptual issues, implementation technical issues, handling of client and server crashes, cross-system issues, performance, and other aspects, and analyzed existing problems.</p><blockquote><em>A universal paradigm should not require programmers to limit themselves to a subset of the chosen programming language, or force them to adopt a certain programming style (for example, don’t use pointers across the board because RPC can’t handle them)</em></blockquote><p>In this critique, the authors gave an example:</p><blockquote><em>Suppose two programmers are working on a project. Programmer 1 is writing the main program. Programmer 2 writes a set of procedures called by the main program. RPC was never mentioned, and both programmers assumed all their code would be compiled and linked into a single executable binary program, running on standalone computers, not connected to any network.</em></blockquote><blockquote><em>At the last minute, after all the code had been thoroughly tested, debugged, and documented, both programmers resigned and left the country, and the code was deployed to run on a distributed system full of surprises. The main program and procedure code run on different computers.</em></blockquote><blockquote><em>Our argument is that because RPC tries to make remote procedure calls look exactly like local procedure calls but cannot do so perfectly, many errors may occur during the call. While many problems can be solved by modifying the code, this loses transparency. Once we acknowledge that true transparency is impossible and programmers must know which calls are remote and which are local, we face the question: are partially transparent mechanisms really better than mechanisms specifically designed for remote access without attempting to make remote computing look local?</em></blockquote><p>At the same time, several other issues were discussed:</p><h4>Two Generals’ Problem</h4><blockquote><em>Networks are unreliable, and it’s impossible to guarantee that data can be transmitted through the network 100% correctly.</em></blockquote><h4>Parameter Issues</h4><blockquote><em>Parameter marshaling, parameter ordering, parameter passing, etc. Especially the passing of pointer-type parameters.</em></blockquote><blockquote><em>Modern RPC typically uses — — — — — — — — — — —</em></blockquote><h4>Global Variables</h4><blockquote><em>Since RPC can be used like local calls, are global variables universal?</em></blockquote><h4>Performance Issues</h4><h4>Exception Handling</h4><blockquote><em>Usually when the main program calls a procedure, if the code is correct, that procedure will eventually return to the caller. If the machine crashes, both the main program and the procedure die, and the entire program must be rerun. Thus, basically there are two modes of operation: the entire program works or the entire program fails.</em></blockquote><blockquote><em>RPC introduces another failure mode: the client works fine, but the server crashes. What should be done if a main program calls a procedure but there’s no response? In some systems, the client would hang forever.</em></blockquote><blockquote><em>Another possibility is to have the client stub start a timer when sending messages to the server. If there’s no response after a certain interval, it tries again and again. After n retries, if it still fails, then it returns an error code indicating the service is unavailable.</em></blockquote><h4>Idempotency Issues</h4><h3>1988: RFC 1057 Published, ONC RPC Defined as Standard RPC Specification</h3><blockquote><em>Sun Microsystems was the first company to provide commercial RPC libraries and RPC compilers. In the mid-1980 s, Sun provided RPC and received support in Sun Network File System (NFS). The protocol was promoted as a standard primarily by Open Network Computing, led by Sun and AT&amp;T. This was a very lightweight RPC system that could be used in most POSIX and POSIX-like operating systems, including Linux, SunOS, OS X, and various BSD release versions. Such systems were known as Sun RPC or ONC RPC. Eventually Sun succeeded, and Sun RPC became the first RPC standard.</em></blockquote><blockquote><em>ONC RPC provided a compiler that required a remote procedure interface definition to generate client and server stub functions. This compiler was called rpcgen. Before running this compiler, programmers had to provide interface definitions. Interface definitions containing function declarations were grouped by version numbers and identified by a unique program code. This program code enabled clients to identify the required interface. Version numbers were very useful, as clients could still connect to a new server even if they hadn’t updated to the latest code, as long as the server still supported the old interface.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*BsLB9iLeLMGTOPDJ.jpeg" /></figure><h4>RPC Call Flow</h4><ol><li>Service consumer (client) calls the service using local call method.</li><li>Client stub receives the call and is responsible for assembling the method, parameters, etc. into a message body that can be transmitted over the network.</li><li>Client stub finds the service address and sends the message to the server.</li><li>Server stub receives the message and decodes it.</li><li>Server stub calls the local service based on the decoded results.</li><li>Local service executes and returns results to the server stub.</li><li>Server stub packages the return results into a message and sends it to the consumer.</li><li>Client stub receives the message and decodes it.</li><li>Service consumer gets the final results.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*JECt5UI7R4TvgqWd.png" /></figure><h4>Service Discovery</h4><p>ONC RPC implements service discovery through a portmapper on the server side. The server registers with the portmapper at startup, and since the portmapper’s port is known to everyone, clients can find the server through the portmapper.</p><p>As the earliest RPC framework, ONC RPC still had many issues:</p><ol><li><strong>Strict Protocol Format Requirements</strong>: The compression format between client and server must be <strong>completely consistent</strong>.</li><li><strong>Inflexible Protocol Modifications</strong>: Both client and server need to make modifications; if only one side makes modifications, RPC will have errors. This leads to version update issues, where each version update basically couples the client and server, requiring simultaneous changes. If the server is not running, the client cannot connect to the remote procedure for calls. Administrators must ensure the server is started before any client attempts to connect to the server. If a new service or interface is added to the system, clients cannot discover it. This requires that those developing the client and server need to be the same group of people, or at least have close communication.</li><li><strong>Function-Oriented</strong>: Object-oriented languages began to rise in the late 1980 s, but the function-oriented ONC RPC didn’t provide any support for features like remote object instantiation from remote classes, tracking object instances, or providing support for polymorphism.</li></ol><h3>1989: Tim Berners-Lee Created the World Wide Web</h3><p>In 1989, Tim Berners-Lee invented the World Wide Web. In September of the following year, he developed the first web browser. By Christmas 1990, Tim Berners-Lee had created all the tools needed to run the World Wide Web: Hypertext Transfer Protocol (HTTP), Hypertext Markup Language (HTML), the first web browser, the first web server, and the first website, achieving the first communication between HTTP client and server. He was awarded the 2016 Turing Award for this achievement.</p><p>By 1995, the Internet had been fully commercialized in the United States.</p><h3>1991: OMG Released CORBA 1.0</h3><blockquote><em>OMG was established in 1989 as a non-profit organization, focusing on developing technically advanced, commercially viable, and vendor-independent software interconnection specifications, promoting object-oriented model technology, and enhancing software portability, reusability, and interoperability. At its founding, members included industry-renowned hardware and software vendors such as Unisys, Sun, Cannon, Hewlett-Packard, and Philips. Currently, the organization has over 800 members.</em></blockquote><p>CORBA (Common Object Request Broker Architecture) is an abstraction for object-oriented languages, developed in C++, allowing communication between different address spaces running on different machines in different languages. CORBA relies on using Interface Definition Language (IDL) to specify interfaces for remote object classes; this IDL is used to generate interfaces for remote system objects on local machines. These IDLs would be used to generate mappings between the abstract interfaces provided by IDL and actual implementations in languages like C++ and Java.</p><p>CORBA attempted to provide several benefits for application developers: <strong>language independence, operating system independence, architecture independence, static types mapping from abstract types in IDL to machine and language-specific implementations of these types, and object transport, where objects could migrate across connections between different machines</strong>. CORBA’s promise was that through the use of mappings, remote calls could appear as local calls, distributed system-related exceptions could be mapped to local exceptions, and handled by local exception handling mechanisms.</p><h3>1994: “A Note on Distributed Computing” Published</h3><p>Jim Waldo and others published a paper titled “A Note on Distributed Computing.” This paper discussed in detail why extending the RPC model to objects was problematic.</p><p>In this paper, the authors argued that ignoring the differences between local and distributed computing was dangerous, and it also discussed a unified object view, listing four major issues in dividing these objects for distributed computing in RPC: communication latency, resolving space separation, partial failures, and concurrency issues (caused by accessing the same remote object through two concurrent client requests). Most of these problems (except partial failures) have an inherent connection with distributed computing itself, but for RPC systems, partial failures mean that RPC systems are not always available.</p><p>The authors also believed that the challenge of distributed computing is not about how to operate online or offline, <strong>and every 10 years, we try to unify local computing and remote computing, and each time we encounter the same problems: remote computing and local computing are different</strong>.</p><p>The authors believed that the main issues with remote computing include:</p><h4>Latency</h4><p>The most obvious difference between local calls and remote calls should be the latency issue: if latency is ignored, it will directly affect software performance. He pointed out that “relying on steady growth in underlying hardware speed” is wrong, and using “real bullets” is not always possible for testing. Performance analysis and relocation are very important, and designs that are optimal at one point may not remain optimal.</p><h4>Partial Failure</h4><p>In local computers, failures can be detected, and the main program has sufficient control. However, this is not the case for distributed computing: remote components may fail, and if partial failure occurs, it cannot be distinguished from connection failure or remote processor failure.</p><p>Waldo believed that if we want to achieve a unified object model, there are only two paths:</p><ol><li>View all objects as local objects</li><li>View all objects as remote objects</li></ol><blockquote><strong><em>But the most important question is not “Can you make remote method calls look like local method calls?” but rather “What is the cost of making remote method calls identical to local method calls?”</em></strong></blockquote><p>This is an issue that cannot be ignored.</p><blockquote><em>Up to this point, we’ve seen that discussions about RPC have mostly been about design, implementation, object-orientation, performance, and how to solve distributed problems. One thing seems to have been ignored, which is usability. Why? Is it because programmers at that time liked complex technology? My former boss once shared during a presentation that he believed not all developers are qualified programmers. Qualified programmers should be like Linus, Dennis, and Tim, who try to change the world and work hard for it. In the early days of the Internet, there were fewer developers, and programmers were a relatively niche elite group, with this type of programmer occupying a larger proportion. When protocols were being established, more consideration was given to how to maximize computer performance, and usability might not have been in the first priority range. However, by the late 90 s, the Internet had begun to popularize, and with the rise of web development, developers grew exponentially. At this time, development frameworks needed to consider not just the user experience of a small group but the user experience of the majority.</em></blockquote><h3>1996: HTTP/1. x Version Released</h3><p>In 1996, HTTP/1.0 was released, greatly enriching HTTP’s transmission content. Besides text, it could also send images, videos, etc., laying the foundation for Internet development.</p><p>Compared to HTTP/0.9, HTTP/1.0 had the following main features:</p><ul><li>Requests and responses support HTTP headers, added status codes, and response objects begin with a response status line</li><li>Protocol version information needs to be sent along with requests, supports HEAD, POST methods</li><li>Supports transmission of content types other than HTML files</li></ul><p>A few months after HTTP/1.0 was released, HTTP/1.1 was published. HTTP/1.1 was more of a refinement of HTTP/1.0</p><h3>1997: OMG Released CORBA 2.0</h3><p>In December 1994, CORBA 2.0 specification was already published. The specification hoped to solve the serious problem of “incompatibility between products developed by different vendors according to the CORBA specification,” but it wasn’t until 1997 that CORBA 2.0 was officially released, and ultimately it failed. As for the reasons for CORBA’s failure, Michi Henning, a technical expert from the CORBA camp and promoter of CORBA technology who later joined the anti-CORBA camp, made the following profound summary in his book “The Rise and Fall of CORBA.”</p><ul><li><strong>Massive and Complex Specifications</strong>: Many features were never implemented, not even conceptually proven; some technical features were impossible to implement, and even if implemented, could not provide portability.</li><li><strong>CORBA’s Learning Curve was Steep</strong>: The platform had a steep learning curve, complex technology, was not easy to use correctly, and these factors led to long development cycles and were error-prone. Early implementations were often full of bugs and lacked quality documentation, and experienced CORBA programmers were scarce.</li><li><strong>Programming Development was Too Complex</strong>: Experienced CORBA developers found writing practical CORBA applications quite difficult. Many APIs were complex, inconsistent, and even felt mysterious, requiring developers to focus on many details. In comparison, the simplicity of component models, such as EJB from the same era, made programming much simpler.</li><li><strong>Expensive</strong>: When using commercial CORBA products, developers generally needed to spend thousands of dollars on developer licenses. Additionally, deploying CORBA products, like deploying Oracle databases, required clients to pay enterprise license fees, and these fees might be linked to the number of applications deployed on the CORBA platform, making it too expensive for many potential clients.</li><li><strong>Sun and Java Became CORBA’s Biggest Competitors</strong>: Commercial companies turned to Sun’s Java and the emerging Web, and began building e-commerce infrastructure based on Web browsers, Java, and EJB.</li><li><strong>The Rise of XML Technology Accelerated CORBA’s Decline</strong>: In the late 1990 s, XML became the new silver bullet in the computer industry, and almost everything defined as XML was considered good. After abandoning DCOM, Microsoft didn’t leave the e-commerce market to competitors, didn’t participate in a war it couldn’t win, but instead used XML to open up a new battlefield.</li></ul><h3>2002: ZeroC Ice Released</h3><blockquote><em>The initial group of technical experts who participated in CORBA were dissatisfied with CORBA’s design and started from scratch to create a new RPC — namely ZeroC Ice, whose initial slogan was “Rebellious Ice.” It has continued to this day, developing into a powerful microservice architecture platform.</em></blockquote><h3>1999: SOAP Released</h3><p>In 1998, XML 1.0 was released and recommended by W 3 C (World Wide Web Consortium) as a standard description language. The same year, Microsoft and DevelopMentor released SOAP (Simple Object Access Protocol), which was subsequently submitted to W 3 C as a standard. SOAP <strong>is a strictly defined information exchange protocol</strong> that uses XML as a new object serialization mechanism for RPC, <strong>used to package remote calls and returns into machine-readable formatted data in Web Services.</strong></p><h4>Protocol Conventions</h4><p>SOAP’s protocol conventions use WSDL (Web Service Description Language), which is a Web service description language. With this, client-side and server-side developers don’t need to communicate face-to-face; as long as they use the WSDL-defined format, when the client knows the WSDL file, they know how to package requests and call services.</p><h4>Transport Protocol</h4><p>SOAP is transported using HTTP, with information containing Header and Body. SOAP’s requests and replies are both placed in messages for transmission.</p><p>SOAP messages are XML-based and have the following main elements:</p><ul><li>Envelope: Required element, defines that the XML document is a SOAP message</li><li>Header: Optional element, contains header information</li><li>Body: Required element, contains all calling and response information</li><li>Fault: Optional element, provides information about errors that occurred during message processing</li></ul><h4>Service Discovery</h4><p>SOAP’s service discovery uses <strong>UDDI</strong> (Universal Description, Discovery, Integration), which acts as a registry center where service providers publish WSDL files to the registry center, and users can search in this registry center.</p><p>SOAP is strictly speaking a variant of XML-RPC (XML Remote Procedure Call) technology. An XML-RPC request message is an HTTP-POST request message with its request message body based on XML format. The client sends XML-RPC request messages to the server, calling remote methods on the server and running remote methods on the server side. After the remote method completes execution, it returns a response message to the client, with its response message body also based on XML format. Remote method parameters support numbers, strings, dates, etc., and also support list arrays and other complex structure types. SOAP was the first truly successful open RPC standard that solved multi-language and multi-platform support.</p><p>However, SOAP also has many shortcomings:</p><ol><li>Low efficiency. Because messages are based on XML, message content has a lot of redundancy in format definition besides data, and the serialization and deserialization parsing speed for XML is also slow.</li><li>It departed from its simple origins, beginning to add layer upon layer of additional concepts beyond simple method calls: adding exception handling, transaction support, security, and digital signatures, making people feel that SOA had become a complex protocol.</li></ol><p>This again aligns with Waldo’s classic conclusion:</p><p><strong>The cost of trying to make remote calls behave like local calls cannot be ignored.</strong></p><p>After this, people began to gradually abandon the procedural, layered concepts in the SOAP standard and started turning towards simpler REST transmission methods.</p><h3>2000: Roy Thomas Fielding Published His Doctoral Dissertation on RESTful Architecture</h3><p>In 2000, Dr. <a href="http://en.wikipedia.org/wiki/Roy_Fielding">Roy Thomas Fielding</a> first introduced the term REST in his doctoral dissertation “<a href="https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm">Architectural Styles and the Design of Network-based Software Architectures</a>”.</p><blockquote><em>REST provides a set of architectural constraints that, when used as a whole, emphasizes the scalability of component interactions, generality of interfaces, independent deployment of components, and intermediary components to reduce interaction latency, while enforcing security and encapsulating legacy systems. — — Roy Fielding</em></blockquote><p>REST is not a protocol but rather an inter-process communication mechanism that uses the HTTP protocol. REST is very simple, requiring no client stub code and server stub code, and can be integrated and implemented in all languages. HTTP REST slowly invaded most of RPC’s application territory as an “anomaly,” and while it led to the extinction of the once-prevalent XML-RPC, it also promoted orthodox RPC technology to enter a new development stage, pursuing higher performance and increasing support for multiple languages and platforms. This became the goal of more and more open-source RPC frameworks, with typical representatives being new open-source frameworks like Thrift and Apache Avro, which are being used by more and more companies in big data systems, large distributed systems, and mobile internet applications.</p><p><strong>In 2008, Vinoski raised our opening question in his paper: “Does developer convenience really trump correctness, scalability, performance, separation of concerns, extensibility, and accidental complexity?”</strong></p><p>Let’s look at the 2020 language rankings to possibly find some answers:</p><p><strong>This chart shows developers’ most loved languages in 2020:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/0*rwKNQ3mkB8-yKasw.png" /></figure><p><strong>This chart shows the most popular languages in 2020:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*q4aTMFHt495LFDkX.png" /></figure><p>Why is Rust, with its steep learning curve and complex design, developers’ favorite?</p><p>Why can JavaScript, which is easy to learn and use but has various language deficiencies, become the most popular language?</p><p><strong>Does developer convenience really trump correctness, scalability, performance, separation of concerns, extensibility, and accidental complexity?</strong></p><p><strong>From developers’ choices, the answer should be YES!</strong></p><p>We can see that since the late 90 s, we entered the era of web development, with Web 1.0, Web 2.0, and Web 3.0 appearing successively. Request/response solutions based on HTTP (XML, REST) began to become popular and captured most of the market. RPC also gradually began to be abandoned by developers and entered a period of silence.</p><p>Of course, RPC didn’t disappear but continued to grow in specific domains. For example, Sun Microsystems’ Network File System (NFS) was built on RPC and was one of the earliest widely adopted distributed file systems.</p><p>With the exponential expansion of the Internet, microservice architecture began to become the industry’s “silver bullet,” and distributed systems began to become ubiquitous. The drawbacks of HTTP-based RESTful began to magnify:</p><ol><li>Only supports request/response style communication</li><li>Challenging to obtain multiple resources in a single request</li><li>Sometimes difficult to map more operations to HTTP verbs</li><li>Messages based on JSON or XML have serious redundancy and low performance</li></ol><p>And RPC, which was born for distributed computing, also began to re-enter developers’ vision.</p><h3>2008: Google Open-sourced Protocol Buffer</h3><p>Protocol Buffers is a lightweight and efficient structured data storage format that can be used for structured data serialization and is very suitable for data storage or RPC data exchange format. It can be used in fields such as communication protocols and data storage as a language-independent, platform-independent, extensible serialized structured data format.</p><p>Protocol Buffers’ main advantages compared to XML and JSON:</p><ul><li>Smaller: Serialized data volume is about 1/3 of JSON, 1/6 of XML</li><li>Faster: Serialization speed is about 7 times faster than JSON, 20 times faster than XML</li><li>Simpler: IDL is clearer and simpler, generated code is easier to use</li><li>Stricter: Strong type definitions, errors can be found at compile time</li></ul><h3>2008: Facebook Open-sourced Thrift</h3><p>Thrift is a cross-language service deployment framework, initially developed by Facebook in 2007 and entered the Apache open-source project in 2008. Thrift defines RPC interfaces and data types through an intermediate language (IDL, Interface Definition Language), and then generates code in different languages through a compiler (currently supports C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, Smalltalk, and OCaml), with the generated code responsible for implementing the RPC protocol layer and transport layer.</p><blockquote><em>Unlike Protocol Buffer, Thrift is not just a data serialization tool but a complete RPC framework. Another difference is that Protobuf standardized a single binary encoding method, but Thrift includes multiple different serialization methods (which Thrift calls protocols).</em></blockquote><h3>2015: HTTP/2.0 Released</h3><p>Although HTTP/1.1 had already optimized many aspects and, as the most widely used protocol version currently, could meet many network needs, as web pages became increasingly complex and even evolved into independent applications, HTTP/1.1 gradually revealed some problems:</p><ul><li>Having to establish new connections for each data transmission, which is particularly unfriendly to mobile devices</li><li>Content transmission in plain text, lacking security</li><li>Large header content with little change between requests, causing waste</li><li>Keep-alive bringing performance pressure to servers</li></ul><p>Between 2010 and 2015, Google demonstrated an alternative way of exchanging data between clients and servers through experimenting with the SPDY protocol. It addressed the focal issues of browser and server-side developers, clarifying the increase in response numbers and solving complex data transmission issues. SPDY eventually evolved into HTTP/2.0 and was released in 2015.</p><ul><li>Using Binary Framing Layer: Added a binary framing layer between the application layer and transport layer to break through HTTP/1.1’s performance limitations, improve transmission performance, and achieve low latency and high throughput without changing HTTP semantics, methods, status codes, URIs, and header fields. On the binary framing layer, HTTP/2.0 divides all transmitted information into smaller messages and frames, encoding them in binary format, where HTTP/1. x header information is encapsulated in Headers frames and request body in Data frames.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*1guxBnV14jQQQBoa.jpeg" /></figure><ul><li>Multiplexing: For HTTP/1. x, even with keep-alive enabled, requests are sent serially, not utilizing bandwidth efficiently even when sufficient bandwidth is available. HTTP/2.0 adopted multiplexing, allowing multiple requests to be sent in parallel, improving bandwidth utilization.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*b0rm8-Kwzy3pF7RF.png" /></figure><ul><li>Data Stream Priority: Since requests can now be sent concurrently, what happens when the browser is waiting for critical CSS or JS files to complete page rendering while the server is focused on sending image resources? HTTP/2.0 allows setting priority values for data streams, determining how clients and servers handle different streams with different priorities.</li><li>Server Push: In HTTP/2.0, servers can send content beyond what was requested to clients. For example, when requesting a page, the server will directly push related files like logos and CSS to the client without waiting for requests, as the server anticipates the client will need these resources. This is equivalent to combining all resources within one HTML document.</li><li>Header Compression: Uses header tables to track and store previously sent key-value pairs, avoiding resending identical content in every request and response.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*aAaXfYtemgkMVc1U.jpeg" /></figure><p>We can see that HTTP/2.0’s new features are very similar to SPDY, as HTTP/2.0 was actually designed based on SPDY and can be considered an upgraded version of SPDY.</p><h3>2015: Google Open-sourced gRPC</h3><p>In 2015, Google open-sourced the <strong>gRPC</strong> framework. gRPC uses Protocol Buffers as its serialization solution and uses HTTP/2 rather than the common TCP for transport medium. gRPC is a multiplexed, bidirectional streaming RPC protocol. In general RPC mechanisms, the client initiates a connection to the server, and only the client can make requests while the server can only respond to incoming requests. However, in bidirectional gRPC streams, although the initial connection is initiated by the client (called endpoint 1), once the connection is established, both the server (called endpoint 2) and endpoint 1 can send requests and receive responses. This greatly simplifies the development of two endpoints communicating with each other (such as in grid computing). Since the two data streams are independent, this also eliminates the hassle of creating two separate connections between endpoints (one from endpoint 1 to endpoint 2, and another from endpoint 2 to endpoint 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/0*QXP7MNx9ist2YbqY.png" /></figure><p>In recent years, several new RPC frameworks have emerged:</p><ul><li>Dubbo: High-performance RPC framework open-sourced by Alibaba</li><li>Motan: Cross-language RPC framework open-sourced by Sina Weibo</li><li>Tars: RPC framework open-sourced by Tencent, supporting multiple languages</li><li>brpc: Industrial-grade RPC framework open-sourced by Baidu</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BL3rv1IUyBEye1VvZIRZ-w.png" /></figure><h3>Summary</h3><p>Looking at RPC’s development over more than forty years, we can draw several important conclusions:</p><h4>Technical Evolution</h4><ul><li>From initial simple procedure calls to supporting object-oriented distributed computing</li><li>From proprietary protocols to open standards (CORBA, SOAP), then to lightweight protocols (Protocol Buffers, Thrift)</li><li>From synchronous call models to supporting asynchronous, streaming, and multiple communication modes</li><li>Serialization methods evolved from text format (XML) to binary format, pursuing higher performance</li></ul><h4>Design Philosophy</h4><ul><li>“Making remote calls as simple as local calls” has always been RPC’s goal</li><li>But as Waldo pointed out in “A Note on Distributed Computing,” this goal has inherent contradictions</li><li>The essential characteristics of distributed computing (latency, partial failure, concurrency) cannot be completely masked</li><li>Need to find balance between usability and the complexity of distributed computing</li></ul><h4>Development Trends</h4><ul><li>Service-oriented and microservice architectures drive RPC frameworks toward greater usability</li><li>Asynchronous programming models receive more attention to handle high-concurrency scenarios</li><li>Service governance, monitoring, and tracing capabilities continue to strengthen</li><li>Cross-language and cross-platform support becomes standard</li><li>Cloud-native era requires better containerization and cluster deployment support</li></ul><h4>Insights</h4><ul><li>Technical solutions need to find balance between ideal and reality</li><li>Development experience and usability are often more important than theoretical perfection</li><li>Successful technical solutions are usually products of pragmatism</li><li>The fundamental problems of distributed computing will exist for a long time, requiring reasonable handling at the application level</li></ul><p>This history tells us that technical evolution is often not linear, but progresses in a spiral through the collision of different ideas. RPC, as infrastructure for distributed computing, will continue to evolve with changes in technical scenarios, but its core issues and trade-offs will always exist. Understanding these essential issues is key to better using and improving RPC technology.</p><h3>Reference Links:</h3><ul><li><a href="https://baike.so.com/doc/6881614-7099104.html">CORBA</a></li><li><a href="https://www.jianshu.com/p/91be39f72c74">Chinese Version of Implementing Remote Procedure Calls</a></li><li><a href="https://developer.51cto.com/art/201906/597963.htm">I Finally Understood RPC Framework After a Week</a></li><li><a href="https://www.cnblogs.com/metoy/p/4321311.html">Detailed Explanation of RPC Principles</a></li><li><a href="https://www.cnblogs.com/houkai/p/9772111.html">Understanding Rest and Rpc</a></li><li><a href="https://www.zhihu.com/question/25536695">Can Someone Explain What is RPC Framework in Simple Terms?</a></li><li><a href="https://www.jianshu.com/p/052913a386b7">What is Rpc</a></li><li><a href="https://www.jianshu.com/p/7d6853140e13">What is Rpc</a></li><li><a href="https://developer.ibm.com/zh/articles/j-cn-java-and-microservice-3/">Microservice Communication</a></li><li><a href="https://developer.ibm.com/zh/articles/cl-evolution-microservices-patterns/">Tracing the Origins: A Brief History of Microservice Pattern Development</a></li><li><a href="https://thrift.apache.org/">https://thrift.apache.org</a></li><li><a href="http://avro.apache.org/">http://avro.apache.org</a></li><li><a href="https://insights.stackoverflow.com/survey/2020#overview">https://insights.stackoverflow.com/survey/2020#overview</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ac410bf5df2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Modern Blog with GitHub Issues: A Step-by-Step Guide to Path Meme]]></title>
            <link>https://medium.com/@amazing_gs/building-a-modern-blog-with-github-issues-a-step-by-step-guide-to-path-meme-d2a84c95aebc?source=rss-d3e03fee4ef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2a84c95aebc</guid>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[blogging]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[goodspeed]]></dc:creator>
            <pubDate>Sat, 02 Nov 2024 04:04:17 GMT</pubDate>
            <atom:updated>2024-11-02T04:04:53.183Z</atom:updated>
            <content:encoded><![CDATA[<p>In the quest for the perfect blogging platform, I often found myself frustrated: existing solutions were either too complex to maintain or too simple to customize. This led me to develop Path Meme — a modern blogging system that uses GitHub Issues as its CMS. Today, I’ll show you how to build your own elegant blog using this system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6DvfsSj9lFHObgqorKVUQ.png" /><figcaption>preview</figcaption></figure><p><strong>Project Links:</strong></p><ul><li>Repository: <a href="https://github.com/gusibi/path-momo-web">https://github.com/gusibi/path-momo-web</a></li><li>Demo: <a href="https://momo.gusibi.mobi/">https://momo.gusibi.mobi</a></li></ul><h3>Why Choose Path Meme?</h3><p>Before we dive into the setup, let me explain why Path Meme might be your ideal choice:</p><ol><li><strong>Minimal Management</strong>: Already familiar with GitHub? Congratulations, you already know how to manage your blog. Publishing a new post is as simple as creating an issue.</li><li><strong>Zero Database Maintenance</strong>: By leveraging GitHub Issues as a CMS, you don’t need to manage a database. All content is safely stored on GitHub.</li><li><strong>Zero Initial Cost</strong>: Using Cloudflare’s free tier, you can run your blog completely free of charge.</li><li><strong>Modern Design</strong>: Inspired by the Path app, the timeline design makes your blog both beautiful and easy to read.</li></ol><h3>Prerequisites</h3><p>Let’s ensure you have everything needed to get started:</p><ol><li><strong>GitHub Account</strong>: Create one at <a href="https://github.com/">GitHub</a> if you haven’t already</li><li><strong>Cloudflare Account</strong>: Sign up for a free account at <a href="https://cloudflare.com/">Cloudflare</a></li><li><strong>Supabase Account</strong>: Register at <a href="https://supabase.com/">Supabase</a> for user authentication</li><li><strong>Node.js</strong>: Ensure you have Node.js installed (v16 or higher recommended)</li></ol><h3>Detailed Setup Process</h3><h3>Step 1: Getting the Project Code</h3><p>First, let’s fork the project to your GitHub account:</p><ol><li>Visit the <a href="https://github.com/gusibi/path-momo-web">Path Meme project</a></li><li>Click the “Fork” button in the top right</li><li>Wait for the fork to complete, and the project will appear in your repository list</li></ol><h3>Step 2: Configuring Cloudflare Pages</h3><p>Cloudflare Pages will provide free static site hosting. Here’s how to set it up:</p><ol><li>Log into your Cloudflare account</li><li>Find “Workers &amp; Pages” in the left menu</li><li>Click “Create application”</li><li>Select “Pages” as the project type</li><li>Click “Connect to Git” and authorize access to your forked repository</li><li>In the deployment settings:</li></ol><ul><li>Set a project name (this will be part of your default domain)</li><li>Set build command to: npm run build</li><li>Set build output directory to: .output/public</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*Wp8ufix7JZES3JImOsGS2Q.png" /></figure><p>💡 <strong>Pro tip</strong>: Choose your project name carefully as it will become part of your default domain (format: your-project.pages.dev)</p><p>At this point, accessing the deployed page will result in an error. Please continue with the configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QsY4FbsvmFd34DiVXRtYuA.png" /></figure><h3>Step 3: Setting Up Supabase</h3><p>Supabase will handle user authentication:</p><ol><li>Log into the Supabase console</li><li>Create a new project:</li></ol><ul><li>Choose a project name</li><li>Select the closest data center</li><li>Set a secure database password</li></ul><p>3. Configure GitHub authentication:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCxvGk_tQ3ynfOFK2QsF2w.png" /></figure><ul><li>Find “Authentication” in the left menu</li><li>Click “Providers”</li><li>Enable the GitHub provider</li><li>Note down the OAuth callback URL</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*24Td0xrKyinU7dMGLAoeVw.png" /></figure><h3>Step 4: Configuring GitHub OAuth</h3><p>Now we need to set up GitHub OAuth:</p><ol><li>Visit <a href="https://github.com/settings/developers">GitHub Developer Settings</a></li><li>Click “New OAuth App”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*OaQ8dbtBwFNB9o3MbRQ6cQ.png" /></figure><ol><li>Fill in the application details:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fM7uK4YyN8TUuSAg6q6OEg.png" /></figure><ul><li>Application name: Your blog name</li><li>Homepage URL: Your Cloudflare Pages URL</li><li>Authorization callback URL: The callback URL from Supabase</li></ul><p>4. After creation, generate and save the Client Secret</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5cz-PMeWfO-krZHGvhxMg.png" /></figure><p>5. After creating a Github OAuth App, you can obtain the Client ID. Click on “Generate a new client secret” to generate a Github client secret</p><p>6. Fill in the generated client ID and client secret into the Supabase Github settings. At this point, the Github login configuration is complete.</p><h3>Step 5: Environment Variables</h3><p>Set up the necessary environment variables in Cloudflare Pages:</p><ol><li>Go to your Pages project settings</li><li>Find the “Environment variables” section</li><li>Add the following variables:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IfMu6GtoHImNvvxHbWzM1A.png" /></figure><pre>SUPABASE_URL=Your Supabase project URL <br>SUPABASE_KEY=Your Supabase public key <br>SITE_URL=Your website URL <br>REPO_OWNER=Your GitHub username <br>REPO_NAME=Your repository name</pre><h3>Daily Usage</h3><p>Once set up, using Path Meme is incredibly straightforward:</p><ol><li><strong>Publishing New Posts</strong>:</li></ol><ul><li>Create a new Issue in your GitHub repository</li><li>Write content using Markdown</li><li>Add labels for categorization</li></ul><p><strong>2. Managing Comments</strong>:</p><ul><li>All Issue comments automatically sync as blog comments</li><li>Manage comments directly on GitHub</li></ul><p><strong>3. Customizing Appearance</strong>:</p><ul><li>Modify site title and description in nuxt.config.ts</li><li>Adjust theme colors and layout</li></ul><h3>Troubleshooting Common Issues</h3><p>You might encounter these situations during use:</p><ol><li><strong>Posts Not Showing?</strong></li></ol><ul><li>Check if the Issue is published (not in draft)</li><li>Verify environment variables are correct</li></ul><p><strong>2. Comment Sync Issues?</strong></p><ul><li>Check GitHub OAuth configuration</li><li>Verify Supabase connection</li></ul><p><strong>3. Style Display Problems?</strong></p><ul><li>Clear browser cache</li><li>Check Cloudflare Pages build logs</li></ul><h3>Conclusion</h3><p>Path Meme’s philosophy is simplicity, elegance, and ease of maintenance. By leveraging the familiar tool of GitHub Issues, we can focus on creating content rather than getting bogged down in technical details.</p><p>Whether you’re a tech blogger, lifestyle writer, or just need a simple personal website, Path Meme can meet your needs. Best of all, the entire setup is free — you only need to invest a little time in the initial configuration.</p><p>If you encounter any issues while using Path Meme, feel free to submit an issue on GitHub or contribute code. Let’s make Path Meme even better together!</p><p><strong>About the Author</strong>: I’m a developer passionate about technology and sharing knowledge. I created Path Meme to help everyone easily own a unique blog space. If you find this project helpful, don’t forget to give it a star on GitHub!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2a84c95aebc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nuxt 3 Beginner-Friendly Guide: Building Your First Application]]></title>
            <link>https://medium.com/@amazing_gs/nuxt-3-beginner-friendly-guide-building-your-first-application-6e20216e3178?source=rss-d3e03fee4ef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e20216e3178</guid>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[quickstart]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[goodspeed]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 04:33:25 GMT</pubDate>
            <atom:updated>2024-10-03T16:39:58.698Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4gx-59JEpFe50ljzurulA.jpeg" /></figure><p>Hey there! Welcome to the world of Nuxt 3!</p><p>If you’re new to web development or just getting started with Nuxt, don’t worry. This guide will walk you through the basics of Nuxt 3 step by step. We’ll explain each concept using simple language and examples, making it easy for you to get started with this powerful Vue. js framework. Ready to begin your Nuxt 3 journey? Let’s dive in!</p><h3>1. Creating Your First Nuxt 3 Application</h3><p>First, let’s start our adventure by creating a brand new Nuxt 3 project! Open your favorite terminal and follow along with these commands:</p><pre>npx nuxi init my-awesome-nuxt-app<br>cd my-awesome-nuxt-app<br>npm install</pre><p>Wow! Just like that, you’ve created your first Nuxt 3 project. But wait, what did these commands actually do? Let me explain:</p><ol><li>npx nuxi init my-awesome-nuxt-app: This command tells npx (an npm package runner) to use nuxi (Nuxt 3&#39;s command-line tool) to initialize a new project. my-awesome-nuxt-app is the name of your project, but of course, you can change it to anything you like!</li><li>cd my-awesome-nuxt-app: This command lets us enter the newly created project folder. cd stands for &quot;change directory&quot;.</li><li>npm install: This command installs all the dependencies needed for your project. Think of it as gathering all the necessary parts to assemble a model.</li></ol><p>Now, let’s take a look at our project structure:</p><pre>my-awesome-nuxt-app/<br>  ├── app.vue<br>  ├── nuxt.config.ts<br>  └── package.json</pre><p>What are these files for? Let me introduce you to these new friends:</p><ul><li>app.vue: This is the main component of your application, where all pages will be rendered. Think of it as the &quot;shell&quot; of your app.</li><li>nuxt.config.ts: This is Nuxt&#39;s configuration file where you can customize Nuxt&#39;s behavior. Think of it as your app&#39;s &quot;control panel&quot;.</li><li>package.json: This file contains metadata about your project and its dependencies. It&#39;s like your project&#39;s &quot;ID card&quot;.</li></ul><p>Let’s take a look at the contents of app.vue:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h1&gt;Welcome to Nuxt 3!&lt;/h1&gt;<br>    &lt;NuxtPage /&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><p>This code does two things:</p><ol><li>Displays a welcome heading.</li><li>The &lt;NuxtPage /&gt; component automatically loads and displays the content of the corresponding page based on the current URL. It&#39;s like a magical placeholder that Nuxt will automatically fill in.</li></ol><p>Congratulations! You’ve successfully created your first Nuxt 3 application. Next, let’s see how to run it and debug it.</p><h3>2. Debug Mode: Your Development Sidekick</h3><p>During development, being able to quickly see changes and catch errors is crucial. Nuxt 3 enables debugging features by default in development mode. Let’s experience it:</p><pre>npm run dev</pre><p>After entering this command, you’ll see some information in the terminal, and finally, it will tell you which address your application is running on, usually <a href="http://localhost:3000.">http://localhost:3000.</a></p><p>Now, open your browser, enter this address, and you’ll see your Nuxt 3 application!</p><p>But wait, what benefits does debug mode actually bring us?</p><ol><li>Hot Reloading: When you modify your code, the browser will automatically refresh to show the latest changes. No more manual page refreshing!</li><li>Vue Devtools: If you’ve installed the Vue Devtools browser extension, you can use it to inspect your component structure, state, and more.</li><li>Detailed Error Messages: If there are errors in your code, Nuxt will display detailed error messages in both the browser console and terminal, helping you quickly locate issues.</li></ol><p>Imagine debug mode as your personal assistant, constantly watching your code and immediately reporting any problems. Doesn’t that make development feel much easier?</p><h3>3. HTML Escaping: Safety First!</h3><p>In web development, security is a very important topic. One common security issue is cross-site scripting (XSS) attacks. Don’t worry, Nuxt 3 has already considered this for you!</p><p>Nuxt 3 uses Vue 3, which automatically escapes HTML in interpolations. This might sound a bit complex, so let me explain with an example:</p><pre>&lt;template&gt;<br>  &lt;div&gt;{{ userInput }}&lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script setup&gt;<br>const userInput = &#39;&lt;script&gt;alert(&quot;This is an XSS attack!&quot;)&lt;/script&gt;&#39;;<br>&lt;/script&gt;</pre><p>In this example:</p><ul><li>&lt;script setup&gt;: This is Vue 3&#39;s Composition API syntax, used to define component logic.</li><li>const userInput: We defined a variable containing potentially dangerous HTML.</li></ul><p>If Nuxt didn’t perform HTML escaping, this code might execute a popup. But don’t worry, Nuxt will automatically convert these special characters into safe forms.</p><p>When this code is rendered, the &lt;script&gt; tag will be escaped and displayed as plain text, rather than being executed as JavaScript. Users will see text like &lt;script&gt;alert(&quot;This is an XSS attack!&quot;)&lt;/script&gt; on the page, instead of a popup alert.</p><p>It’s like Nuxt has installed a security filter for your application, ensuring that user input doesn’t accidentally become executable code.</p><p>Remember, although Nuxt provides this layer of protection, you should still remain vigilant when handling user input. Security is a complex topic, and this is just one aspect of it.</p><h3>4. Routing: Making Your Application Accessible</h3><p>In Nuxt 3, routing is like a map for your application, telling Nuxt what content to display when users visit different URLs. The best part is, Nuxt uses a “file-based routing system”, which means your file structure determines your routes! Sounds a bit magical, right? Let’s explore together.</p><p>First, create a pages folder, then add some .vue files inside:</p><pre>pages/<br>  ├── index.vue<br>  └── about.vue</pre><p>Just like that, you’ve created two routes:</p><ul><li>/: corresponds to pages/index.vue</li><li>/about: corresponds to pages/about.vue</li></ul><p>Let’s see what the content of index.vue might look like:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h1&gt;Welcome to my Nuxt 3 app!&lt;/h1&gt;<br>    &lt;p&gt;This is the home page.&lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><p>And about.vue might look like this:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h1&gt;About Us&lt;/h1&gt;<br>    &lt;p&gt;We&#39;re an awesome team using Nuxt 3!&lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><p>But wait, what if we want dynamic routes? For example, a user profile page with the user ID in the URL? Nuxt has thought of this too!</p><p>Create a file pages/users/[id].vue:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h1&gt;User Profile&lt;/h1&gt;<br>    &lt;p&gt;User ID: {{ $route.params.id }}&lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;&lt;script setup&gt;<br>const route = useRoute();<br>console.log(route.params.id);<br>&lt;/script&gt;</pre><p>What’s happening here?</p><ul><li>[id].vue: The square brackets indicate this is a dynamic parameter.</li><li>{{ $route.params.id }}: In the template, we can access route parameters via $route.params.</li><li>useRoute(): This is a composable function used to access the current route in &lt;script setup&gt;.</li></ul><p>Now, when users visit /users/1, /users/2, etc., this page will be displayed, and the id parameter will be passed to the component.</p><p>Doesn’t routing feel super simple? You just need to create files, and Nuxt will automatically handle all the routing logic for you. This is the magic of Nuxt!</p><h3>5. Static Files: Handling Images and Other Assets</h3><p>In web development, handling static files like images, fonts, or other asset files is very common. Nuxt 3 provides us with a simple way to handle these files.</p><p>First, create a public folder in your project root directory. This folder is special because Nuxt will directly map its contents to your website&#39;s root directory.</p><p>Let’s try it out:</p><ol><li>Create an images folder inside the public folder.</li><li>Put an image named logo.png into the images folder.</li></ol><p>Now your file structure might look like this:</p><pre>my-awesome-nuxt-app/<br>  ├── public/<br>  │   └── images/<br>  │       └── logo.png<br>  ├── app.vue<br>  ├── nuxt.config.ts<br>  └── package.json</pre><p>Great! Now you can use this image in your Vue components. Let’s modify app.vue:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;img src=&quot;/images/logo.png&quot; alt=&quot;My Logo&quot;&gt;<br>    &lt;h1&gt;Welcome to my Nuxt 3 app!&lt;/h1&gt;<br>    &lt;NuxtPage /&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><p>Notice the src attribute:</p><ul><li>/images/logo.png: This path is relative to the server root path, no need to include public.</li></ul><p>When you run your application, you should see the logo image displayed on the page. Isn’t it simple?</p><p>This method not only works for images but also for any static files you want to serve directly to the browser, such as robots.txt, favicon.ico, etc.</p><p>This approach has several benefits:</p><ol><li>Simple and intuitive: You don’t need to remember complex paths, just remember the file’s location in the public directory.</li><li>Performance optimization: Nuxt will automatically handle these static files, ensuring they can be loaded efficiently.</li><li>Deployment-friendly: When you deploy your application, these files will be automatically processed, you don’t need extra configuration.</li></ol><p>Remember, the public directory is not just for images. You can place any type of static file here, such as font files, robots. txt, favicon. ico, etc. Nuxt will ensure that all these files can be accessed correctly.</p><h3>6. Rendering Templates: The Magic of Components</h3><p>In modern frontend development, componentization is a very important concept. It allows us to break down the interface into small, reusable parts, just like Lego blocks. Nuxt 3 fully embraces this idea, let’s see how to create and use components.</p><p>First, let’s create a simple user card component. Create a components folder in the project root directory, then create a UserCard.vue file inside:</p><pre>&lt;template&gt;<br>  &lt;div class=&quot;user-card&quot;&gt;<br>    &lt;img :src=&quot;user.avatar&quot; :alt=&quot;user.name&quot; class=&quot;user-avatar&quot;&gt;<br>    &lt;h2&gt;{{ user.name }}&lt;/h2&gt;<br>    &lt;p&gt;{{ user.email }}&lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script setup&gt;<br>defineProps([&#39;user&#39;]);<br>&lt;/script&gt;<br>&lt;style scoped&gt;<br>.user-card {<br>  border: 1px solid #ccc;<br>  border-radius: 8px;<br>  padding: 16px;<br>  margin: 16px 0;<br>  text-align: center;<br>}<br>.user-avatar {<br>  width: 100px;<br>  height: 100px;<br>  border-radius: 50%;<br>}<br>&lt;/style&gt;</pre><p>Let me explain the different parts of this component:</p><ol><li>&lt;template&gt;: This defines the HTML structure of the component. We used some dynamic bindings (:src and :alt) and interpolation ({{ }}) to display user information.</li><li>&lt;script setup&gt;: This is Vue 3&#39;s Composition API syntax. defineProps([&#39;user&#39;]) declares that this component accepts a user prop.</li><li>&lt;style scoped&gt;: This defines the styles for the component. The scoped attribute ensures these styles only apply to this component and don&#39;t affect other places.</li></ol><p>Now, let’s use this component in a page. Modify pages/index.vue:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h1&gt;User List&lt;/h1&gt;<br>    &lt;UserCard v-for=&quot;user in users&quot; :key=&quot;user.id&quot; :user=&quot;user&quot; /&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script setup&gt;<br>const users = ref([<br>  { id: 1, name: &#39;John Doe&#39;, email: &#39;john@example.com&#39;, avatar: &#39;https://placekitten.com/100/100&#39; },<br>  { id: 2, name: &#39;Jane Smith&#39;, email: &#39;jane@example.com&#39;, avatar: &#39;https://placekitten.com/101/101&#39; },<br>]);<br>&lt;/script&gt;</pre><p>What’s happening here?</p><ol><li>We imported and used the UserCard component. Note that we don&#39;t need to explicitly import it - Nuxt will automatically import components from the components folder.</li><li>We use the v-for directive to loop through and render the user list. Each UserCard receives a user object as a prop.</li><li>:key=&quot;user.id&quot; provides a unique key for each list item, which helps Vue optimize rendering.</li><li>ref([...]) creates a reactive array containing user data. In a real application, this data might come from an API call.</li></ol><p>Now, when you run your application, you should see a nice list of users, each displayed in a card.</p><p>What are the benefits of componentization?</p><ol><li>Reusability: You can reuse the UserCard component anywhere in your application.</li><li>Maintainability: If you need to modify the appearance of the user card, you only need to change it in one place.</li><li>Testability: You can test the UserCard component in isolation, ensuring it works correctly in various scenarios.</li></ol><p>This is the magic of componentization! It makes your code cleaner, more efficient, and easier to manage. As your application grows, you’ll find componentization becomes a powerful tool for building complex interfaces.</p><h3>7. State Management: Keeping Your Data Tidy</h3><p>As your application becomes more complex, managing state (i.e., your application data) becomes increasingly important. Nuxt 3 provides a simple yet powerful way to manage state, called “Nuxt State”.</p><p>Let’s look at how to use it through a simple counter example.</p><p>First, create a new file composables/useState.js:</p><pre>export const useCounter = () =&gt; useState(&#39;counter&#39;, () =&gt; 0);</pre><p>What does this code do?</p><ul><li>useState: This is a function provided by Nuxt 3 for creating a reactive state.</li><li>&#39;counter&#39;: This is a unique identifier for the state. If multiple components use the same identifier, they will share the same state.</li><li>() =&gt; 0: This is the initial value of the state. Here, our counter starts at 0.</li></ul><p>Now, let’s use this state in a component. Create a new component components/Counter.vue:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;p&gt;Count: {{ count }}&lt;/p&gt;<br>    &lt;button @click=&quot;increment&quot;&gt;Increase&lt;/button&gt;<br>    &lt;button @click=&quot;decrement&quot;&gt;Decrease&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script setup&gt;<br>const count = useCounter();<br>function increment() {<br>  count.value++;<br>}<br>function decrement() {<br>  count.value--;<br>}<br>&lt;/script&gt;</pre><p>Let’s break down this component:</p><ol><li>We use useCounter() to get the counter state.</li><li>count.value is used to access and modify the state value. Note the use of .value, this is because count is a reactive reference.</li><li>increment and decrement functions are used to increase and decrease the count respectively.</li></ol><p>Now, you can use this Counter component in any page or component. For example, modify pages/index.vue:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h1&gt;Nuxt 3 Counter Example&lt;/h1&gt;<br>    &lt;Counter /&gt;<br>    &lt;Counter /&gt; &lt;!-- Note that we used the Counter component twice --&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><p>When you run this application, you’ll see two counters. Interestingly, they share the same state! If you increase one counter, the other will change too. This is the power of shared state.</p><p>What are the advantages of this approach?</p><ol><li>Simple: You don’t need to set up complex state management libraries.</li><li>Flexible: You can easily share state between different components.</li><li>Reactive: Changes in state are automatically reflected everywhere it’s used.</li></ol><p>State management might seem a bit abstract, but it’s key to building large, complex applications. As you continue your Nuxt 3 journey, you’ll find more and more scenarios where shared state is useful.</p><p>Remember, while this approach is sufficient for simple to moderately complex applications, Nuxt 3 is also fully compatible with state management libraries like Pinia for more complex state management needs.</p><h3>8. Asynchronous Data Fetching: Talking to the Backend</h3><p>In real-world applications, we often need to fetch data from a server. Nuxt 3 provides two powerful composables for handling asynchronous data fetching: useFetch and useAsyncData. Today, we&#39;ll mainly look at useFetch as it&#39;s simpler and more straightforward.</p><p>Let’s create a simple blog post list page to demonstrate how to use useFetch.</p><p>Create a new file pages/posts.vue:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h1&gt;Blog Posts&lt;/h1&gt;<br>    &lt;div v-if=&quot;pending&quot;&gt;Loading...&lt;/div&gt;<br>    &lt;div v-else-if=&quot;error&quot;&gt;Error: {{ error.message }}&lt;/div&gt;<br>    &lt;ul v-else&gt;<br>      &lt;li v-for=&quot;post in posts&quot; :key=&quot;post.id&quot;&gt;<br>        {{ post.title }}<br>      &lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script setup&gt;<br>const { data: posts, pending, error } = await useFetch(&#39;https://jsonplaceholder.typicode.com/posts&#39;)<br>&lt;/script&gt;</pre><p>Let’s break down this code:</p><ol><li>useFetch: This function is used to fetch data from an API. In this example, we&#39;re using a free online API to get blog post data.</li><li>{ data: posts, pending, error }: Here we&#39;re using destructuring assignment. useFetch returns multiple values, and we&#39;re only taking what we need.</li></ol><ul><li>data is renamed to posts, containing the data returned by the API.</li><li>pending indicates whether the data is still loading.</li><li>error will contain error information if something goes wrong.</li></ul><ol><li>v-if, v-else-if, v-else: These are Vue&#39;s conditional rendering directives. We use them to display different content based on the loading state of the data.</li><li>v-for=&quot;post in posts&quot;: This directive is used to loop through and render the list of posts.</li></ol><p>What does this component do? When the page loads, it will:</p><ol><li>Display a “Loading…” message.</li><li>Fetch blog post data from the API.</li><li>If successful, display the list of posts.</li><li>If there’s an error, display the error message.</li></ol><p>The beauty of useFetch is that it automatically handles many complex scenarios:</p><ul><li>It supports server-side rendering (SSR), meaning data can be fetched on the server side, improving initial load times.</li><li>It automatically handles loading states and error handling.</li><li>It caches results by default, avoiding unnecessary repeated requests.</li></ul><p>Pro tip: In a real application, you might want to add more interactivity, like clicking on a post title to navigate to a post details page. You can combine this with the routing knowledge we learned earlier to achieve this!</p><p>Asynchronous data fetching is a crucial part of building modern web applications. With Nuxt 3’s useFetch, it becomes simple yet powerful. Remember, practice is the best way to master these concepts. Try modifying this example, perhaps fetching different types of data, or adding some extra functionality?</p><p>Alright, let’s continue exploring more features of Nuxt 3!</p><h3>9. Custom Error Page: Handling Errors Gracefully</h3><p>Errors are inevitable in any application. However, we can improve the user experience by creating a friendly error page. Nuxt 3 makes this very simple.</p><p>Create an error.vue file in your project root directory:</p><pre>&lt;template&gt;<br>  &lt;div class=&quot;error-page&quot;&gt;<br>    &lt;h1&gt;Oops! Something went wrong&lt;/h1&gt;<br>    &lt;p&gt;{{ error.message }}&lt;/p&gt;<br>    &lt;button @click=&quot;handleError&quot;&gt;Return to Home&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script setup&gt;<br>const props = defineProps({<br>  error: Object<br>})<br>const handleError = () =&gt; {<br>  clearError({ redirect: &#39;/&#39; })<br>}<br>&lt;/script&gt;<br>&lt;style scoped&gt;<br>.error-page {<br>  display: flex;<br>  flex-direction: column;<br>  align-items: center;<br>  justify-content: center;<br>  height: 100vh;<br>  text-align: center;<br>}<br>&lt;/style&gt;</pre><p>Let’s break down this component:</p><ol><li>defineProps: This function is used to define the component&#39;s props. Here, we expect to receive an error object.</li><li>error.message: This will display the specific error message.</li><li>handleError: This function uses clearError to clear the error and redirect the user to the home page.</li><li>&lt;style scoped&gt;: These styles center the error page content, making it look more appealing.</li></ol><p>Now, whenever your application encounters an error, Nuxt will automatically display this error page. This includes not only errors in your code but also 404 “Page Not Found” errors.</p><p>To test this error page, you can intentionally introduce an error in one of your components. For example, modify pages/index.vue:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h1&gt;Home Page&lt;/h1&gt;<br>    {{ nonExistentVariable.property }}<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><p>When you visit the home page, you’ll see our custom error page because nonExistentVariable doesn&#39;t exist.</p><p>What are the benefits of a custom error page?</p><ol><li>Improved User Experience: Friendly error messages can reduce user frustration.</li><li>Brand Consistency: You can design an error page that matches your application’s style.</li><li>Provide Solutions: You can include helpful links or actions on the error page to help users resolve the issue.</li></ol><p>Remember, while we hope users never see the error page, a well-designed error page can greatly improve the user experience when errors do occur.</p><h3>10. Middleware: Your Route Guard Hero</h3><p>Imagine middleware as a security guard standing at the door of your pages. It can check the visitor’s “pass” and decide whether to let them enter the page. Super cool, right?</p><p>Let’s see how to create a simple authentication middleware:</p><ol><li>Create a file middleware/auth.js:</li></ol><pre>export default defineNuxtRouteMiddleware((to, from) =&gt; {<br>  // Assume we have an isLoggedIn variable to check if the user is logged in<br>  const isLoggedIn = true; // In a real app, this should be an actual authentication check<br>  // If the user is not logged in and trying to access a page other than the login page<br>  if (!isLoggedIn &amp;&amp; to.path !== &#39;/login&#39;) {<br>    // Let&#39;s send them to the login page!<br>    return navigateTo(&#39;/login&#39;);<br>  }<br>});</pre><p>Isn’t this code interesting? It’s like a little doorkeeper, checking if the user has a “VIP pass” (is logged in). If not, it politely escorts them to the login page.</p><p>So, how do we use this middleware? There are two ways:</p><ol><li>Apply globally: Add to nuxt.config.ts:</li></ol><pre>export default defineNuxtConfig({<br>  router: {<br>    middleware: [&#39;auth&#39;]<br>  }<br>});</pre><p>This way, every page will go through this middleware check.</p><ol><li>Use on specific pages:</li></ol><pre>&lt;script setup&gt;<br>definePageMeta({<br>  middleware: &#39;auth&#39;<br>});<br>&lt;/script&gt;</pre><p>This way, only this page will use the middleware. Pretty flexible, right?</p><h3>11. Plugins: Give Your Nuxt App Superpowers</h3><p>Plugins are like giving your Nuxt application new superpowers. They can add global functionality when your app starts up. Let’s create a simple plugin:</p><ol><li>Create a file plugins/myPlugin.js:</li></ol><pre>export default defineNuxtPlugin((nuxtApp) =&gt; {<br>  nuxtApp.provide(&#39;myPlugin&#39;, {<br>    sayHello: (name) =&gt; `Hello, ${name}! Welcome to the world of Nuxt 3!`<br>  });<br>});</pre><p>This plugin adds a globally available sayHello method. Pretty neat, right?</p><p>Now, you can use this plugin in any component:</p><pre>&lt;script setup&gt;<br>const { $myPlugin } = useNuxtApp();<br>const message = $myPlugin.sayHello(&#39;Nuxter&#39;);<br>&lt;/script&gt;<br>&lt;template&gt;<br>  &lt;div&gt;{{ message }}&lt;/div&gt;<br>&lt;/template&gt;</pre><p>Run this code, and you’ll see a friendly greeting message: “Hello, Nuxter! Welcome to the world of Nuxt 3!”</p><p>Doesn’t it feel super easy to add new functionality to your app?</p><h3>12. SSR and SSG: Make Your Website Fly</h3><p>Nuxt 3 supports both Server-Side Rendering (SSR) and Static Site Generation (SSG). This might sound complicated, but don’t worry, let’s break it down:</p><ul><li>SSR: The server generates the page every time someone visits your website. This is useful for websites that need real-time data.</li><li>SSG: All pages are pre-generated, and visitors get static files. This is super fast for websites where content doesn’t change often!</li></ul><p>To configure these features, just add a few lines to your nuxt.config.ts:</p><pre>export default defineNuxtConfig({<br>  ssr: true, // Enable server-side rendering<br>  target: &#39;static&#39; // or &#39;server&#39;, to configure deployment target<br>});</pre><p>If you want to generate a fully static website, just run:</p><pre>npm run generate</pre><p>This command will generate a website that you can deploy to any static hosting service. Super convenient, right?</p><p>Remember, Rome wasn’t built in a day. Similarly, mastering these advanced features takes time and practice. Start small, take it slow, and you’ll discover the power of Nuxt 3!</p><p>If you’re confused about any part or want to dive deeper into a topic, don’t be shy, just ask me! The best way to learn new things is to stay curious and ask questions.</p><p>Next, we’ll explore Nuxt 3’s multilingual support and deployment strategies. Are you ready? Let’s continue our Nuxt 3 adventure!</p><h3>13. Multilingual Support: Make Your App Speak Multiple Languages</h3><p>In this globalized era, having your app support multiple languages is a cool feature. Although Nuxt 3 doesn’t have a built-in internationalization solution, we can use the @nuxtjs/i18n module to achieve this functionality. Let&#39;s go through it step by step:</p><ol><li>First, install the @nuxtjs/i18n module:</li></ol><pre>npm install @nuxtjs/i18n@next</pre><p>2. Then, configure it in nuxt.config.ts:</p><pre>export default defineNuxtConfig({<br>  modules: [&#39;@nuxtjs/i18n&#39;],<br>  i18n: {<br>    locales: [<br>      { code: &#39;en&#39;, iso: &#39;en-US&#39;, file: &#39;en.json&#39; },<br>      { code: &#39;zh&#39;, iso: &#39;zh-CN&#39;, file: &#39;zh.json&#39; },<br>    ],<br>    defaultLocale: &#39;en&#39;,<br>    langDir: &#39;locales/&#39;,<br>    strategy: &#39;prefix_except_default&#39;,<br>  }<br>})</pre><p>This configuration might look a bit complex, let me explain:</p><ul><li>locales: This defines the languages we support. In this example, we support English and Chinese.</li><li>defaultLocale: Sets the default language to English.</li><li>langDir: Specifies the directory where language files are stored.</li><li>strategy: Defines the URL strategy. Here, we use &#39;prefix_except_default&#39;, which means URLs for languages other than the default will have a language prefix. For example, a Chinese page URL might be /zh/about.</li></ul><p>3. Create language files:</p><p>Create en.json and zh.json in the locales directory:</p><pre>// en.json<br>{<br>  &quot;welcome&quot;: &quot;Welcome to my awesome Nuxt 3 app!&quot;,<br>  &quot;about&quot;: &quot;About&quot;<br>}<br>// zh.json<br>{<br>  &quot;welcome&quot;: &quot;欢迎来到我超酷的 Nuxt 3 应用！&quot;,<br>  &quot;about&quot;: &quot;关于&quot;<br>}</pre><p>4. Use in components:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h1&gt;{{ $t(&#39;welcome&#39;) }}&lt;/h1&gt;<br>    &lt;nuxt-link :to=&quot;localePath(&#39;about&#39;)&quot;&gt;{{ $t(&#39;about&#39;) }}&lt;/nuxt-link&gt;<br>    &lt;button @click=&quot;switchLanguage&quot;&gt;Switch Language&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script setup&gt;<br>const { t, locale } = useI18n();<br>const switchLanguage = () =&gt; {<br>  locale.value = locale.value === &#39;en&#39; ? &#39;zh&#39; : &#39;en&#39;;<br>};<br>&lt;/script&gt;</pre><p>Here, the $t function is used for text translation, localePath is used to generate localized route paths. The switchLanguage function allows users to switch languages.</p><p>That’s it! Now your app can speak multiple languages. Doesn’t it feel like your app just became more international?</p><h3>14. Deployment: Let Your Nuxt 3 App Soar to the Cloud</h3><p>After creating an awesome app, the next step is to let the whole world see it. This is the deployment process. Nuxt 3 offers multiple deployment options, let’s take a look:</p><h3>a. Static Hosting: Simple and Fast</h3><p>If your app doesn’t need server-side rendering or API routes, static hosting is a great choice.</p><ol><li>Generate static files:</li></ol><pre>npm run generate</pre><p>This command will generate static files in the .output/public directory.</p><ol><li>Deploy: You can upload the .output/public directory to any static file hosting service, such as Netlify, Vercel, or GitHub Pages. It&#39;s that simple!</li></ol><h3>b. Node. js Server: More Control</h3><p>If you need server-side rendering or API routes, you can choose to deploy to a Node. js environment.</p><ol><li>Build the app:</li></ol><pre>npm run build</pre><p>2. Start the server:</p><pre>node .output/server/index.mjs</pre><p>You can deploy this to any platform that supports Node. js, such as Heroku or DigitalOcean.</p><h3>c. Using PM 2: Keep Your App Running Non-Stop</h3><p>For production environments, you might want to use a process manager like PM 2:</p><pre>npm install -g pm2<br>pm2 start .output/server/index.mjs</pre><p>PM 2 can help you manage and monitor your application, ensuring it’s always running.</p><h3>d. Docker: Package the Entire Environment</h3><p>Docker allows you to package your application along with its entire runtime environment. Create a Dockerfile:</p><pre>FROM node:16<br>WORKDIR /app<br>COPY . .<br>RUN npm install<br>RUN npm run build<br>EXPOSE 3000<br>CMD [&quot;node&quot;, &quot;.output/server/index.mjs&quot;]</pre><p>Then build and run the Docker image:</p><pre>docker build -t my-nuxt-app .<br>docker run -p 3000:3000 my-nuxt-app</pre><p>This way, your application will run in the same environment no matter where it’s deployed.</p><h3>e. Serverless Deployment: Scale on Demand</h3><p>Nuxt 3 also supports serverless deployment. For example, deploying to Vercel is very simple:</p><ol><li>Install Vercel CLI: npm i -g vercel</li><li>Run the vercel command and follow the prompts</li></ol><p>It’s that easy!</p><h4>Environment Variables: Protect Your Secrets</h4><p>When deploying, it’s important to manage environment variables correctly. In Nuxt 3, you can use .env files or runtime configuration.</p><p>Create a .env file:</p><pre>API_BASE_URL=https://api.example.com</pre><p>In nuxt.config.ts:</p><pre>export default defineNuxtConfig({<br>  runtimeConfig: {<br>    apiSecret: &#39;&#39;, // Only available on the server side<br>    public: {<br>      apiBase: &#39;&#39; // Available on both client and server side<br>    }<br>  }<br>})</pre><p>Using environment variables:</p><pre>const config = useRuntimeConfig()<br>console.log(config.apiSecret) // Only on server side<br>console.log(config.public.apiBase) // On client and server side</pre><p>This way, you can safely manage your API keys and other sensitive information.</p><p>Remember, choosing which deployment method to use depends on your application’s needs and your team’s skills. Don’t be afraid to try different methods to find the one that suits you best!</p><p>Well, our journey through Nuxt 3’s advanced features ends here. You now have a grasp of middleware, plugins, multilingual support, and deployment basics. These tools will make your Nuxt 3 development journey smoother.</p><p>Remember, learning is an ongoing process. Don’t expect to master everything at once. Take it slow, practice these concepts step by step. Soon, you’ll become a Nuxt 3 expert!</p><p>If you have any questions, or want to dive deeper into a topic, feel free to ask me. Learning new technology should be fun, so enjoy your Nuxt 3 journey!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e20216e3178" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Modern Blog with Cloudflare Workers and GitHub Issues]]></title>
            <link>https://medium.com/@amazing_gs/build-a-modern-blog-with-cloudflare-workers-and-github-issues-e4eb05297150?source=rss-d3e03fee4ef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4eb05297150</guid>
            <dc:creator><![CDATA[goodspeed]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 15:26:18 GMT</pubDate>
            <atom:updated>2024-09-04T15:26:18.234Z</atom:updated>
            <content:encoded><![CDATA[<p>In the era of dynamic web applications, finding a balance between simplicity and functionality can be challenging. Enter Path Meme: a modern, sleek blogging system that combines the power of Cloudflare Workers with GitHub Issues to create a streamlined and efficient content management system. Inspired by the clean design of the Path app, Path Meme offers a timeline-style blog display with features like Markdown rendering, tag classification, and GitHub reaction statistics. Here’s how you can set up your very own Path Meme blog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RdEyfBvxWe6SMxZPUs_ZRw.png" /><figcaption>demo</figcaption></figure><h3>Features</h3><ul><li><strong>GitHub Issues as CMS</strong>: Manage your blog posts directly from GitHub Issues.</li><li><strong>Timeline Blog Display</strong>: Present your content in a chronological timeline.</li><li><strong>Markdown Rendering</strong>: Write your posts in Markdown for easy formatting.</li><li><strong>Tag Classification</strong>: Organize your posts with tags.</li><li><strong>GitHub Reactions</strong>: Track and display reactions from GitHub.</li><li><strong>Night Mode</strong>: Enjoy a dark theme for comfortable reading.</li><li><strong>Responsive Design</strong>: Ensure your blog looks great on all devices.</li></ul><h3>Getting Started</h3><h3>Prerequisites</h3><ul><li>GitHub Account</li><li>Cloudflare Account</li><li>Basic Command Line Knowledge</li></ul><h3>Step-by-Step Guide</h3><p><strong>1 Fork the Project</strong></p><ul><li>Log in to your GitHub account.</li><li>Click the “fork” icon at the top right of the repository.</li></ul><p><strong>2 Set Up Cloudflare Worker</strong></p><ul><li>Log in to your Cloudflare account.</li><li>Navigate to the “Workers” page.</li><li>Click “Create a Worker” and name it path-meme-api.</li><li>Paste the code from worker/index.js into the editor.</li><li>Click “Save and Deploy” to create your worker.</li><li>Note the generated Worker URL for future use. It will look like <a href="https://{your-worker-path}.workers.dev/api/blog-posts.">https://{your-worker-path}.workers.dev/api/blog-posts.</a></li></ul><p><strong>3 Configure GitHub Personal Access Token</strong></p><ul><li>In GitHub, go to Settings &gt; Developer settings &gt; Personal access tokens.</li><li>Click “Generate new token.”</li><li>Provide a descriptive name, select “repo” scope, and generate the token.</li><li>Copy the token for later use.</li></ul><p><strong>4 Update Cloudflare Worker</strong></p><ul><li>Go back to your Cloudflare Worker settings.</li><li>Add the following variables:</li><li>GITHUB_TOKEN with the value of your GitHub Personal Access Token.</li><li>GITHUB_OWNER with your GitHub username.</li><li>GITHUB_REPO with the repository you are using.</li><li>Click “Deploy” to apply the changes.</li></ul><p><strong>5 Clone the Repository Locally</strong></p><ul><li>Open your terminal and run:</li></ul><pre>git clone https://github.com/your-username/path-style-blog.git cd path-style-blog</pre><p><strong>6 Update API URL in Frontend Code</strong></p><ul><li>In public/script.js, update the fetch request URL to your Cloudflare Worker URL.</li></ul><p><strong>7 Commit and Push Changes</strong></p><ul><li>Run the following commands:</li></ul><pre>git add . git commit -m &quot;update API URL&quot; git push origin main</pre><p><strong>8 Set Up Cloudflare Pages</strong></p><ul><li>In Cloudflare, go to the “Pages” page.</li><li>Click “Create a project.”</li><li>Choose “Connect to Git” and select your GitHub repository.</li><li>In the build settings, leave the build command empty and set the build output directory to “public.”</li><li>Click “Save and Deploy.”</li></ul><p><strong>9 Create Blog Posts</strong></p><ul><li>In your chosen GitHub repository, go to the “Issues” tab.</li><li>Click “New issue” and write your blog post in Markdown.</li><li>Add tags as needed and click “Submit new issue.”</li></ul><p><strong>10 Visit Your Blog</strong></p><ul><li>Open the Cloudflare Pages URL for your project to view your blog.</li></ul><h3>Customization</h3><ul><li><strong>Banner Image</strong>: Add your banner image to the public folder and update the path in index.html.</li><li><strong>Profile Picture</strong>: Similarly, add your profile picture to the public folder and update the path in index.html.</li><li><strong>Styling</strong>: Customize the look of your blog by modifying styles.css.</li><li><strong>Features</strong>: Enhance functionality by updating script.js and worker/index.js.</li></ul><h3>Troubleshooting</h3><ul><li><strong>Posts Not Displaying</strong>: Check Cloudflare Worker logs to ensure API requests are successful.</li><li><strong>GitHub Token Issues</strong>: Verify that your GitHub Personal Access Token has the correct permissions and is not expired.</li><li><strong>Styling Issues</strong>: Check Cloudflare Pages deployment logs to confirm all files are uploaded correctly.</li></ul><h3>Contributing</h3><p>We welcome pull requests to improve this project. For major changes, please open an issue to discuss your proposed modifications.</p><p>demo: <a href="https://momo.gusibi.mobi/">https://momo.gusibi.mobi/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4eb05297150" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoid These Mistakes: Best Practices for Deploying Hugo on Vercel]]></title>
            <link>https://medium.com/@amazing_gs/avoid-these-mistakes-best-practices-for-deploying-hugo-on-vercel-da2c10d4f503?source=rss-d3e03fee4ef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/da2c10d4f503</guid>
            <category><![CDATA[blogging]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[hugo]]></category>
            <category><![CDATA[vercel]]></category>
            <dc:creator><![CDATA[goodspeed]]></dc:creator>
            <pubDate>Wed, 21 Feb 2024 14:49:15 GMT</pubDate>
            <atom:updated>2024-02-21T14:50:14.320Z</atom:updated>
            <content:encoded><![CDATA[<p>I have recently been creating a <a href="http://www.sora-vedio.com/">Sora Video collection website</a> using Hugo and deploying it on Vercel. I encountered some issues during the deployment process, and here is a brief summary.</p><h3>Install Hugo</h3><p>You can visit the official Hugo website to install Hugo. On macOS, I used brew to install it.</p><blockquote>brew install hugo</blockquote><h3>Build in Local</h3><p>I used a theme called Hinode (<a href="https://gethinode.com/">https://gethinode.com/</a>), which is a clean documentation and blog theme for Hugo based on Bootstrap 5.</p><ol><li>Create a new site</li></ol><blockquote>hugo new site my-hinode-site &amp;&amp; cd my-hinode-site</blockquote><p>2. Initialize the module system</p><blockquote>hugo mod init example.com/my-hinode-site<br>echo “[[module.imports]]” &gt;&gt; hugo.toml<br>echo “path = ‘github.com/gethinode/hinode’” &gt;&gt; hugo.toml</blockquote><p>3. Start a development server</p><blockquote>hugo server</blockquote><h3>Deploy with Vercel</h3><p>After pushing the code to GitHub, I associated the repository with Vercel to deploy the site. However, after the successful deployment, the site always showed an XML page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*soKc31Ws6XgTdcaZW436ZA.png" /></figure><p>Upon checking the deployment logs, I received the following error message:</p><blockquote>found no layout file for “HTML” for kind “page”: You should create a template file which matches Hugo Layouts Lookup Rules for this combination.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ZsPl1VYxvG46frDgigA_Q.png" /></figure><p>I tried deploying the site using the official Hugo template, and it worked fine. Initially, I thought it was an issue with the theme, so I reached out to the theme’s author for help.</p><p><a href="https://github.com/gethinode/hinode/discussions/789">https://github.com/gethinode/hinode/discussions/789</a></p><p>However, the author had not encountered this problem before.</p><p>Then I ran the official Vercel template locally and encountered an error. It dawned on me that it might be a version issue with Hugo.</p><p>After searching, I found that it is possible to specify the Hugo version during the Vercel deployment.</p><p><a href="https://discourse.gohugo.io/t/vercel-tips/34766">https://discourse.gohugo.io/t/vercel-tips/34766</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*S1-YGOEO5YndRYgzP8Y7rw.png" /></figure><p>After modifying the version, the deployment started successfully. If you encounter the error message ‘Error: failed to load modules: failed to download modules: binary with name “go” not found,’ you can add the following command to the Install Command to install Golang.</p><blockquote>amazon-linux-extras install golang1.19</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*8zDu13TJZoTzVrrsGjUjzg.png" /></figure><p>That’s it! The deployment was successful.🎉🎉🎉🎉🎉🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aNjwHKJd-g9mxxkSH96cDA.png" /></figure><h3><strong>Reference Links</strong></h3><p>origin link：<a href="https://blog.gusibi.site/article/Best-Practices-for-Deploying-Hugo-on-Vercel">https://blog.gusibi.site/article/Best-Practices-for-Deploying-Hugo-on-Vercel</a></p><p>1. <a href="https://discourse.gohugo.io/t/vercel-tips/34766">https://discourse.gohugo.io/t/vercel-tips/34766</a> 2.<a href="https://github.com/vercel/vercel/discussions/5834">https://github.com/vercel/vercel/discussions/5834</a> 3.<a href="https://github.com/vercel/vercel/discussions/10889">https://github.com/vercel/vercel/discussions/10889</a> 4.<a href="https://vercel.com/docs/deployments/build-image#installing-go-in-the-build-image">https://vercel.com/docs/deployments/build-image#installing-go-in-the-build-image</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da2c10d4f503" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter markdown: Using Markdown with Cross-Line Selection in Flutter]]></title>
            <link>https://medium.com/@amazing_gs/flutter-markdown-using-markdown-with-cross-line-selection-in-flutter-0660dc34ec27?source=rss-d3e03fee4ef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0660dc34ec27</guid>
            <category><![CDATA[markdown]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <dc:creator><![CDATA[goodspeed]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 15:57:22 GMT</pubDate>
            <atom:updated>2024-01-08T14:53:18.426Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Master Markdown and Multi-line Selection in Flutter: A Step-by-Step Tutorial</strong></h3><p>Recently, I have been developing <a href="https://github.com/gusibi/moli_ai">Moli AI</a> and it requires support for markdown rendering and multi-line copying. This article primarily covers the following topics:</p><blockquote>How to use markdown in Flutter.</blockquote><blockquote>How to customize markdown styles.</blockquote><blockquote>How to enable multi-line selection in markdown.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*RB8Tv4WFWzKPObIfH1IrvA.gif" /></figure><h3>flutter_markdown</h3><blockquote>flutter_markdown is a markdown renderer provided by the official Flutter community. It supports creating rich text output from simple Markdown tagged formatted plain text data, including text styles, tables, links, and more.</blockquote><p>Overview:</p><ul><li>The flutter_markdown package allows you to render Markdown text into rich text in Flutter.</li><li>It is built on the Dart markdown package and parses Markdown into an abstract syntax tree (AST).</li><li>Markdown allows injecting HTML into the source text, but the flutter_markdown package does not support inline HTML.</li><li>By default, the flutter_markdown package uses the GitHub Flavored Markdown specification.</li></ul><p>How to use:</p><ol><li>Add the flutter_markdown: ^0.6.18+3 dependency in your pubspec.yaml file.</li></ol><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flutter_markdown: ^0.6.18+3</pre><p>Then add the following code:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_markdown/flutter_markdown.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  // This widget is the root of your application.<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Flutter Demo&#39;,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>        useMaterial3: true,<br>      ),<br>      home: const MyHomePage(title: &#39;Flutter Markdown Page&#39;),<br>    );<br>  }<br>}<br><br>class MyHomePage extends StatefulWidget {<br>  const MyHomePage({super.key, required this.title});<br><br>  final String title;<br><br>  @override<br>  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();<br>}<br><br>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    var markdown = &quot;&quot;&quot;<br>Here&#39;s a simple Go program that prints &quot;Hello, world!&quot; to the console😀:<br><br>```go<br>package main<br>import &quot;fmt&quot;<br><br>func main() {<br>    fmt.Println(&quot;Hello, world!&quot;)<br>}```<br><br>Save the above code in a file with a `.go` extension, for example `hello.go`. Then, you can run the program by executing the following command in your terminal:<br><br>```shell<br>go run hello.go```<br><br>The output will be:<br><br>```Hello, world!```<br>&quot;&quot;&quot;;<br>    return Scaffold(<br>        appBar: AppBar(<br>          backgroundColor: Theme.of(context).colorScheme.inversePrimary,<br>          title: Text(widget.title),<br>        ),<br>        body: Center(<br>          child: Markdown(<br>            selectable: true,<br>            data: markdown,<br>          ),<br>        ));<br>  }<br>}</pre><p>The resulting output can be seen in the image below. Markdown is rendered correctly, but the code does not have any special styles and multi-line selection is not supported.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*SZsN4wCtAOZbOa_npIJyRQ.gif" /></figure><p>Now, let’s see how to customize code styles.</p><h3>How to customize styles:</h3><h4><strong>Use the </strong><strong>styleSheet property</strong></h4><p>Use the styleSheet property to customize the default styles of Markdown. You can use the TextStyle object to specify font, color, size, and other properties.</p><p>Here is the modified code where the color of the code block has been changed. It sets the font size of h1 headings to 24 pixels, the font size of code to 14 pixels, and the color to green.</p><pre>body: Center(<br>          child: Markdown(<br>            selectable: true,<br>            data: markdown,<br>            // new start<br>            styleSheet: MarkdownStyleSheet(<br>              h1: const TextStyle(fontSize: 24, color: Colors.blue), <br>              code: const TextStyle(fontSize: 14, color: Colors.green),// new end<br>            ),<br>          ),<br>        ));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*HmqhXr4phXbifr5YY8NchA.png" /></figure><p>Let’s further optimize the styles:</p><pre>body: Center(<br>          child: Markdown(<br>            selectable: true,<br>            data: markdown,<br>            styleSheet: MarkdownStyleSheet(<br>              h1: const TextStyle(fontSize: 24, color: Colors.blue),<br>              code: const TextStyle(<br>                  fontSize: 14,<br>                  color: Colors.white,<br>                  backgroundColor: Colors.grey),<br>              codeblockPadding: const EdgeInsets.all(8),<br>              codeblockDecoration: BoxDecoration(<br>                borderRadius: BorderRadius.circular(4),<br>                color: Colors.grey,<br>              ),<br>            ),<br>          ),<br>        )</pre><p>Here, I have used codeblockPadding and codeblockDecoration.</p><ul><li>codeblockPadding controls the padding of the code block. You can use the EdgeInsets object to specify horizontal, vertical, left, right, top, and bottom padding properties.</li></ul><pre>MarkdownStyleSheet(<br>  codeblockPadding: EdgeInsets.all(8),<br>)</pre><p>This sets the padding of the code block to 8 pixels.</p><ul><li>codeblockDecoration controls the decoration of the code block. You can use the BoxDecoration object to specify background color, borders, corner radius, and other properties.</li></ul><pre>MarkdownStyleSheet(<br>  codeblockDecoration: BoxDecoration(<br>    borderRadius: BorderRadius.circular(4),<br>    color: Colors.grey,<br>  ),<br>)</pre><p>This sets the background color of the code block to gray and adds rounded borders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*upqV9-1u8GAxeT77Yrri8A.gif" /></figure><p>However, multi-line copying is still not supported. This may be because flutter_markdown uses many separate widgets to render Markdown, which may not be compatible with each other.</p><h4>How to enable multi-line selection:</h4><p>To solve the issue of multi-line selection, we can use the flutter_markdown_selectionarea package.</p><p>To use it just replace flutter_markdown dependency in your pubspec.yaml with</p><pre>flutter_markdown_selectionarea: ^0.6.17+1</pre><p>and then change all imports from</p><pre>import &#39;package:flutter_markdown/flutter_markdown.dart&#39;;</pre><p>to</p><pre>import &#39;package:flutter_markdown_selectionarea/flutter_markdown.dart&#39;;</pre><p>and then you will be able to make multiple paragraphs selectable by using SelectionArea widget:</p><pre>SelectionArea(<br>  child: MarkdownBody(data: text),</pre><p>Here is the modified code:</p><pre>body: Center(<br>          child: SelectionArea( // new<br>            child: Markdown(<br>              // selectable: true, // remove<br>              data: markdown,<br>              styleSheet: MarkdownStyleSheet(<br>                h1: const TextStyle(fontSize: 24, color: Colors.blue),<br>                code: const TextStyle(<br>                    fontSize: 14,<br>                    color: Colors.white,<br>                    backgroundColor: Colors.grey),<br>                codeblockPadding: const EdgeInsets.all(8),<br>                codeblockDecoration: BoxDecoration(<br>                  borderRadius: BorderRadius.circular(4),<br>                  color: Colors.grey,<br>                ),<br>              ),<br>            ),<br>          ),<br>        ));</pre><p>Now, multi-line selection is supported.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*DUM22_m9slHscDn2ozEswg.gif" /></figure><h3>One More Thing</h3><p>Although multi-line selection is supported, you may notice that the color of the selected code block does not change, which can be confusing and make it uncertain whether it is actually selected.</p><p>To address this, I used Flutter Markdown’s MarkdownElementBuilder to customize the rendering of Markdown.</p><p>To use MarkdownElementBuilder, you need to create a subclass of MarkdownElementBuilder and implement the visitElementAfter() method. In the visitElementAfter() method, you can generate custom Flutter components based on the type of Markdown element.</p><p>Here is a simple example:</p><pre>class CodeElementBuilder extends MarkdownElementBuilder {<br>  // To determine whether the code is an inline code block or a code block<br>  bool isCodeBlock(md.Element element) {<br>    if (element.attributes[&#39;class&#39;] != null) {<br>      return true;<br>    } else if (element.textContent.contains(&quot;\n&quot;)) {<br>      return true;<br>    }<br>    return false;<br>  }<br><br>  @override<br>  Widget? visitElementAfter(md.Element element, TextStyle? preferredStyle) {<br>    if (!isCodeBlock(element)) {<br>      return Container(<br>        padding: const EdgeInsets.all(2),<br>        child: Text(<br>          element.textContent,<br>          style: TextStyle(<br>              fontSize: 16,<br>              fontStyle: FontStyle.italic,<br>              color: preferredStyle!.color),<br>        ),<br>      );<br>    } else {<br>      return Container(<br>        margin: const EdgeInsets.all(10),<br>        child: Text(<br>          element.textContent,<br>          style: const TextStyle(fontSize: 16, color: Colors.white),<br>        ),<br>      );<br>    }<br>  }<br>}</pre><pre>body: Center(<br>          child: SelectionArea(<br>            child: Markdown(<br>              data: markdown,<br>              builders: {<br>                &#39;code&#39;: CodeElementBuilder(), // new<br>              },<br>              styleSheet: MarkdownStyleSheet(<br>                h1: const TextStyle(fontSize: 24, color: Colors.blue),<br>                code: const TextStyle(<br>                    fontSize: 14,<br>                    color: Colors.pink,<br>                    backgroundColor: Colors.grey),<br>                codeblockPadding: const EdgeInsets.all(8),<br>                codeblockDecoration: BoxDecoration(<br>                  borderRadius: BorderRadius.circular(4),<br>                  color: Colors.grey,<br>                ),<br>              ),<br>            ),<br>          ),<br>        )</pre><p>From the image below, you can clearly see which content is selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*2Hq5yhR8Sm2I_4ggMqVcZQ.gif" /></figure><p>🎉🎉🎉</p><h4>Remaining issues:</h4><ol><li>How to highlight code blocks.</li><li>How to select code blocks after highlighting.</li></ol><h3>Relevant links ：</h3><ol><li><a href="https://github.com/gusibi/flutter_learn/tree/main/flutter_markdown_example">https://github.com/gusibi/flutter_learn/tree/main/flutter_markdown_example</a></li><li><a href="https://pub.dev/packages/flutter_markdown">flutter_markdown</a></li><li><a href="https://pub.dev/packages/flutter_markdown_selectionarea">https://pub.dev/packages/flutter_markdown_selectionarea</a></li><li><a href="https://github.com/flutter/flutter/issues/99819">[flutter_markdown] Selecting text works only paragraph by paragraph in markdown widget when text is not indented</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0660dc34ec27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Flutter Guide: How to Implement Dark Mode, Dynamic Theming and Theme Switching]]></title>
            <link>https://medium.com/@amazing_gs/complete-flutter-guide-how-to-implement-dark-mode-dynamic-theming-and-theme-switching-ddabaef48d5a?source=rss-d3e03fee4ef7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddabaef48d5a</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[goodspeed]]></dc:creator>
            <pubDate>Sun, 03 Sep 2023 13:19:24 GMT</pubDate>
            <atom:updated>2024-11-02T02:20:12.020Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>I have been learning Flutter development recently. Theme switching is an important way to enhance user experience and is a topic that cannot be ignored in learning Flutter. This article will explain in detail how to implement theme switching in Flutter.</p><h3>Main Contents</h3><p>This article mainly covers the following topics:</p><ul><li>Why apps need to support theme switching</li><li>How to set themes in Flutter</li><li>How to switch between day and night modes in Flutter</li><li>How to dynamically change color themes in Flutter</li><li>How to implement dynamic theme switching using Provider</li></ul><h3>Why Apps Need to Support Theme Switching</h3><ul><li>Enhance user experience: Different users have different aesthetic preferences. Theme switching can satisfy more users’ visual preferences.</li><li>Personalized experience: Theme switching can demonstrate the personalized characteristics of the app and allow users to customize themes to personalize their experience.</li><li>Assist accessibility: Switching to high contrast themes can improve accessibility for users with visual impairments.</li></ul><h3>How to Set Themes in Flutter</h3><p>Setting themes in Flutter is very simple, just configure the theme parameters. Even if no theme is set, Flutter will use the default theme. Like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*4sUWu5OaX5yceA0ObbgIQw.png" /></figure><p>If you want to use dark mode, just add darkTheme: ThemeData.dark().</p><pre>class MainApp extends StatelessWidget {<br>  const MainApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      theme: ThemeData(<br>          colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.green)),<br>      darkTheme: ThemeData.dark(),<br>      home: Scaffold(<br>        appBar: AppBar(<br>          title: const Text(&quot;AppBar&quot;),<br>        ),<br>        body: const Center(<br>          child: Text(&#39;Hello World!&#39;),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>This way the app will automatically change the theme mode based on the system setting. If you want to manually specify the theme mode, you can set themeMode: ThemeMode.light in the code. This will force the app&#39;s theme mode to be light mode.</p><h3>How to set Material 3</h3><p>Setting Material 3 is even simpler, just specify useMaterial3: true.</p><pre>class MainApp extends StatelessWidget {<br>  const MainApp({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      theme: ThemeData.light(useMaterial3: true,),<br>      darkTheme: ThemeData.dark(),<br>      home: Scaffold(<br>        appBar: AppBar(<br>          title: const Text(&quot;AppBar&quot;),<br>        ),<br>        body: const Center(<br>          child: Text(&#39;Hello World!&#39;),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><blockquote>All the example code below uses Material 3.</blockquote><p>Material 3 allows users to set the entire color theme of an application from a single seed color. By setting the color scheme seed parameter in your theme constructor, Flutter will generate a harmonious color scheme for each widget in your app from this entry.<br>For example, the color scheme below is generated using colorSchemeSeed: const Color.fromARGB(86, 80, 14, 171),:</p><pre>class MainApp extends StatelessWidget {<br>  const MainApp({super.key});<br> @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      theme: ThemeData(<br>        useMaterial3: true,<br>        colorSchemeSeed: const Color.fromRGBO(86, 80, 14, 171),<br>      ),<br>      darkTheme: ThemeData(<br>        useMaterial3: true,<br>        brightness: Brightness.dark,<br>        colorSchemeSeed: const Color.fromRGBO(86, 80, 14, 171),<br>      ),<br>      themeMode: ThemeMode.dark,<br>      home: const HomePage(),<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*T52xE3tb_y2R5HAZVxMqew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*tuwA1dwC2fRfjhlyIZrzAg.png" /></figure><h3>How to Switch Between Day and Night Modes in Flutter</h3><p>In an app, day mode and night mode refer to the display styles of the app. Day mode typically uses bright colors and high contrast, while night mode uses dark backgrounds and low contrast.</p><p>Day mode is commonly used when using the app in bright environments, because the bright colors and high contrast help users view content more easily. Night mode is commonly used when using the app in dim environments, because the dark backgrounds and low contrast can reduce eye strain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*2zyd9D-e4c6Z35u_2xPpeg.gif" /></figure><p>In Flutter, dynamically switching between day and night modes is very simple, just add an intermediate variable to store the theme mode.</p><p>The steps to implement mode switching are:</p><ol><li>Define two sets of themes for day and night;</li><li>Add a ThemeMode variable to store the current theme mode;</li><li>Switch the theme mode by setting this variable to light/dark;</li><li>After switching, the interface will automatically rebuild to apply the new theme.</li></ol><p>The specific code is as follows:</p><pre>class _MainAppState extends State&lt;MainApp&gt; {<br>  ThemeMode themeMode = ThemeMode.system;<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp( <br>      theme: ThemeData(<br>        useMaterial3: true,<br>      ),<br>      darkTheme: ThemeData(<br>        useMaterial3: true,<br>        brightness: Brightness.dark,<br>      ),<br>      themeMode: themeMode,  // MaterialApp reads theme mode variables to switch themes.<br>      home: Scaffold(<br>        appBar: AppBar(<br>          title: const Text(&quot;AppBar&quot;),<br>        ),<br>        body: Column(<br>          children: [<br>            Row(<br>              children: [<br>                TextButton(<br>                    onPressed: () {<br>                      setState(() {<br>                        themeMode = ThemeMode.light;<br>                      });<br>                    },<br>                    child: const Text(&quot;light&quot;)),<br>                TextButton(<br>                    onPressed: () {<br>                      setState(() {<br>                        themeMode = ThemeMode.dark;<br>                      });<br>                    },<br>                    child: const Text(&quot;dark&quot;)),<br>              ],<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>This code defines a simple Flutter app with light and dark themes. It first defines a ThemeMode variable themeMode and initializes it to ThemeMode. system. This means the app will use the system’s default theme, which is typically light theme on Android and dark theme on iOS.</p><p>Next, the light and dark themes are defined. The light theme uses the ThemeData class. The useMaterial3 property is set to true to use the new Material 3 design language. The colorSchemeSeed property is set to a specific color which will be used as the base color for the theme.</p><p>The dark theme is defined similarly, except the brightness property is set to Brightness.dark.</p><p>Finally, the MaterialApp widget is used to create the app. The theme property is set to the light theme, and the themeMode property is set to the themeMode variable. This means the app will launch with the light theme, but users can switch the theme to dark by tapping the respective buttons.</p><p>The Scaffold widget is used to create the basic layout of the app. The appBar property is used to create the app bar, and the backgroundColor is set to the primary container color of the current theme. The body property is used to create the main content of the app, which in this case is a simple list with two buttons.</p><p>The two buttons are used to change the theme. When the user taps the “light” button, the themeMode variable is set to ThemeMode.light, switching the app to the light theme. When the user taps the “dark” button, themeMode is set to ThemeMode.dark, switching to the dark theme.</p><h3>How to Dynamically Change Color Themes in Flutter</h3><h3>How to Set Color Themes</h3><p>There are two ways to configure color themes for a Flutter app:</p><ol><li>Using tokens to set theme colors</li><li>Using a custom color scheme</li></ol><h3>Using Tokens to Set Theme Colors</h3><p>In Flutter’s Material Design, a “token” is a concept related to the design system, especially in Google’s “Material You” system. In this system, tokens are a set of parameters used to define the look and feel of an app. These can include colors, fonts, shapes and various other elements to create a consistent visual experience in the app.</p><p>A token is an abstract concept that can be thought of as a variable or identifier representing a specific visual style. For example, a color token could represent the primary color of the theme, while a font token could represent the headline font used in the app. This helps ensure the visual styles in the app adhere to Material Design requirements and that styles are consistent across different pages and components.</p><p>In Flutter, you can set these tokens using ThemeData. For example, you can set the primary color and accent color of your app using the primaryColor and accentColor properties of ThemeData. Similarly, you can set font styles throughout the app using textTheme.</p><p>For Material 3, you can use the following approach to set color tokens which can be reused across the entire app instead of redefining them:</p><pre>ThemeData(<br>        useMaterial3: true,<br>        colorSchemeSeed: const Color.fromRGBO(86, 80, 14, 171),<br>      )</pre><h3>Using a Custom Color Scheme</h3><p>In Flutter, you can customize a Material-style color scheme by following these steps:</p><ol><li>Create a colors.dart file and define color variables inside, for example:</li></ol><pre>import &#39;package:flutter/material.dart&#39;;<br>const lightColorScheme = ColorScheme(<br>  brightness: Brightness.light,<br>  primary: Color(0xFF96416A),<br>  onPrimary: Color(0xFFFFFFFF),<br>  primaryContainer: Color(0xFFFFD8E6),<br>  onPrimaryContainer: Color(0xFF3D0024),<br>  secondary: Color(0xFF735761),<br>  ...<br>);<br>const darkColorScheme = ColorScheme(<br>  brightness: Brightness.dark,<br>  primary: Color(0xFFFFB0D0),<br>  onPrimary: Color(0xFF5C113B),<br>  primaryContainer: Color(0xFF792952),<br>  onPrimaryContainer: Color(0xFFFFD8E6),<br>  secondary: Color(0xFFE1BDCA),<br>  onSecondary: Color(0xFF412A33),<br>  ...<br>);</pre><ol><li>Reference these custom colors in the theme:</li></ol><pre>class MyApp extends StatelessWidget {<br>  const MyApp({Key? key}) : super(key: key);<br>// This widget is the root of your application.<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      theme: ThemeData(useMaterial3: true, colorScheme: lightColorScheme),<br>      darkTheme: ThemeData(useMaterial3: true, colorScheme: darkColorScheme),<br>      home: const Home(),<br>    );<br>  }<br>}</pre><ol><li>Import colors.dart into the page to which you want to apply the theme, and get the theme setting component style through Theme.of(context):</li></ol><pre>final defaultColorScheme = Theme.of(context).colorScheme;<br>appBar: AppBar(<br>        title: const Text(&quot;AppBar&quot;),<br>        backgroundColor: defaultColorScheme.primaryContainer,<br>      ),</pre><p>4, you can also create multiple themes, when switching themes, pass in different ThemeData objects:</p><pre>MaterialApp(<br>  theme: lightTheme, <br>  darkTheme: darkTheme,<br>)</pre><p>5 Customize other styles in the theme, such as fonts, shapes, shadows, etc.</p><p>In this way, we can freely combine colors and visual effects without diving deep into Material source code, to achieve a customized, brand-specific theme.</p><blockquote>A simple way to generate color schemes is to use the material Theme Builder, which can customize a set of color schemes based on the selected color tokens.</blockquote><blockquote><a href="https://m3.material.io/theme-builder#/custom">https://m3.material.io/theme-builder#/custom</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*ekAvAGKVuYuCQb0WEbnxlA.gif" /></figure><h3>How to Dynamically Change Theme Colors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*JQFs1GLX1gGM8T3roPhRmQ.gif" /></figure><p>There are many ways to dynamically switch theme colors in an app. Today I will mainly introduce a recommended approach — using Provider.</p><p>Provider allows centralized state management of the theme, so the theme can be changed dynamically.</p><ol><li>Create a ThemeProvider class responsible for state management;</li><li>Set up ThemeProvider in root page;</li><li>Get instance through Consumer in pages;</li><li>Call set method to modify theme config;</li><li>Theme change triggers interface update.</li></ol><h3>1. Create Theme Provider</h3><p>First we create a ThemeProvider class to hold the theme state:</p><pre>// theme_provider.dart<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;color_schemes.g.dart&#39;;<br>class ThemeProvider with ChangeNotifier {<br>  late ThemeMode _themeMode = ThemeMode.system;<br>  late ColorScheme _darkScheme = darkColorScheme;<br>  late ColorScheme _lightScheme = lightColorScheme;<br>  ThemeMode get themeMode =&gt; _themeMode;<br>  void setThemeMode(ThemeMode value) {<br>    _themeMode = value;<br>    notifyListeners();<br>  }<br>  ColorScheme get darkScheme =&gt; _darkScheme;<br>  void setDarkScheme(ColorScheme value) {<br>    _darkScheme = value;<br>    notifyListeners();<br>  }<br>  ColorScheme get lightScheme =&gt; _lightScheme;<br>  void setLightScheme(ColorScheme value) {<br>    _lightScheme = value;<br>    notifyListeners();<br>  }<br>}</pre><p>This code implements a ThemeProvider that can dynamically modify the light and dark themes of the app.</p><h3>2. Provide ThemeProvider</h3><p>Then provide this ThemeProvider in the root page:</p><pre>Widget build(BuildContext context) {<br>    return ChangeNotifierProvider(<br>        create: (context) =&gt; ThemeProvider(),<br>        child:<br>            Consumer&lt;ThemeProvider&gt;(builder: (context, themeProvider, child) {<br>          return MaterialApp(<br>            theme: ThemeData(<br>                useMaterial3: true, colorScheme: themeProvider.lightScheme),<br>            darkTheme: ThemeData(<br>                useMaterial3: true, colorScheme: themeProvider.darkScheme),<br>            themeMode: themeProvider.themeMode,<br>            home: const HomePage(),<br>          );<br>        }));<br>  }</pre><p>This implementation has the following advantages:</p><ol><li>In MaterialApp, get the instance of ThemeProvider through Consumer.</li><li>The color schemes in LightTheme and DarkTheme directly reference the lightScheme and darkScheme in ThemeProvider.</li><li>The theme mode (themeMode) also directly references the themeMode state in ThemeProvider.</li><li>When the state in ThemeProvider changes, it will trigger Consumer to rebuild dynamically through notifyListeners to switch themes.</li><li>In the home page or other pages, you can get the ThemeProvider instance through context and call its setter methods to change the theme mode and theme colors.</li><li>By extracting the theme data and state using Provider, it is simply reused in the UI layer, achieving loosely coupled dynamic theme switching.</li><li>ThemeProvider is responsible for theme state management, the UI layer is responsible for display. The separation of responsibilities follows design principles.</li></ol><h3>3. Get ThemeProvider</h3><p>In pages that need it, get the provider instance:</p><pre>final themeProvider = Provider.of&lt;ThemeProvider&gt;(context);</pre><h3>4. Change Theme</h3><p>Call setLightScheme and setDarkScheme to change the theme colors:</p><pre>themeProvider.setLightScheme(lightColorScheme); <br>themeProvider.setDarkScheme(darkColorScheme);</pre><p>This allows sharing and modifying theme configurations across different pages through the provider. Managing themes using Provider avoids duplicate code and provides reactive theme configuration. This is a flexible and concise way to implement dynamic theming in Flutter.</p><blockquote>To use provider, you need to first add the provider dependency. The specific code is as follows — first add provider: ^6.0.5 in the dev_dependencies section of your pubspec.yaml file:</blockquote><pre>dev_dependencies:<br>  flutter_test:<br>    sdk: flutter<br>  flutter_lints: ^2.0.0<br>  provider: ^6.0.5</pre><h3>Summary</h3><p>Flutter provides powerful theme customization capabilities through its theming system. We can freely switch themes in various ways to enrich app experiences and accessibility. Mastering Flutter’s theming mechanisms is an important part of developing high-quality apps.</p><p>The above provides a comprehensive introduction to implementing theme switching in Flutter. If you have any other questions, feel free to leave a comment for discussion.</p><p>For example, the theme toggle button can call setters on the ThemeProvider to switch theme modes. Other components can obtain the ThemeProvider instance via Provider to modify styles.</p><p>With Provider managing theme state reactively, widgets can rebuild automatically when themes change. This enables dynamic runtime theming without needing to manually handle app-wide theme updates. Overall, Flutter makes it straightforward to customize and dynamically switch themes for delightful user experiences.</p><h3>reference links</h3><ul><li><a href="https://m3.material.io/theme-builder#/custom">https://m3.material.io/theme-builder#/custom</a></li><li><a href="https://juejin.cn/post/7078583859536723975">https://juejin.cn/post/7078583859536723975</a></li><li><a href="https://docs.flutter.dev/cookbook/design/themes">Flutter Theming ↗</a> — Official Flutter documentation on theming.</li><li><a href="https://medium.com/flutter-community/dynamic-theming-in-flutter-609f84212e6d">Dynamic Theming in Flutter ↗</a> — Tutorial on implementing runtime theme switching using Provider.</li><li><a href="https://www.youtube.com/watch?v=RIOlw_heRrU">Flutter: Dynamic Themes ↗</a> — Video tutorial on dynamic themes with simple app example.</li><li><a href="https://pub.dev/packages/provider">Provider Package ↗</a> — Pub page for the Provider state management package.</li><li><a href="https://flatteredwithflutter.com/using-themes-in-flutter/">Using Themes in Flutter ↗</a> — Guide on defining theme data and styling apps.</li><li><a href="https://m3.material.io/">Material Design Theming ↗</a> — Official Material design system theming resources.</li><li><a href="https://www.woolha.com/tutorials/flutter-web-theme-switching-example-using-provider">Theme Switching in Flutter Web ↗</a> — Implementing theme toggle on Flutter web.</li><li><a href="https://gusibi-blog.vercel.app/article/flutter-theme-switching-guide">https://gusibi-blog.vercel.app/article/flutter-theme-switching-guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddabaef48d5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>