<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: atanda nafiu</title>
    <description>The latest articles on DEV Community by atanda nafiu (@atanda0x).</description>
    <link>https://dev.to/atanda0x</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1081168%2F060a903a-2d04-4638-a728-1f71b3755aa2.jpeg</url>
      <title>DEV Community: atanda nafiu</title>
      <link>https://dev.to/atanda0x</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/atanda0x"/>
    <language>en</language>
    <item>
      <title>Build Performant Servers with gRPC and Protocol Buffers</title>
      <dc:creator>atanda nafiu</dc:creator>
      <pubDate>Thu, 24 Aug 2023 12:36:08 +0000</pubDate>
      <link>https://dev.to/atanda0x/build-performant-servers-with-grpc-and-protocol-buffers-4jb</link>
      <guid>https://dev.to/atanda0x/build-performant-servers-with-grpc-and-protocol-buffers-4jb</guid>
      <description>&lt;p&gt;Streaming large data set have a heavy cost on memory and performance in I/O. The modern serialized and deserialized data method uses protocol buffers, which Google designed. Due to the popularity of microservice architecture systems, it's been difficult to communicate between systems using other communication models as services. Protocol buffers were designed to beat the likes of JSON and XML by removing the responsibility performed by these formats. gRPC is also a communication model that takes the protocol buffer format further. To simplify the developer experience and improve efficiency, gRPC API should uses a protocol buffer for API definition.&lt;/p&gt;

&lt;h1&gt;
  
  
  What are Protocol Buffers
&lt;/h1&gt;

&lt;blockquote&gt;
&lt;p&gt;"Protocol buffers are a flexible, efficient, automated mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once. Then you can use specially generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages. You can even update your data structure without breaking deployed programs compiled against the "old" format.”  — Google&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Protocol buffers, commonly known as Protobuf, are packages designed by Google to serialize structured data like JSON and XML, but strictly typed. Protobuf helps structure data and can be used in languages like Go, Java, Python, etc. Protobuf is crucial in microservices, where much data is transferred across services.&lt;/p&gt;

&lt;h1&gt;
  
  
  Why Protocol Buffers are Needed
&lt;/h1&gt;

&lt;p&gt;Modern server architectures like gRPC, REST, and GraphQL need fast parsing of serialised and deserialised structured data. Protobuf is used for communication protocols that generate thousands of messages and are available in many languages.&lt;/p&gt;

&lt;p&gt;Protobufs help serialized structured data format for packet types that are large messages in size. The data format is used for long-term data storage. Information changes, including new files and deleting existing fields to any protobuf without updating the existing data. Protobuf is used primarily for interchanging structure information, inter-server communication, and archival data storage on disk. Facebook also used a similar protocol called Apache Thrift, and Amazon created ION. Microsoft also used the Bond protocol, offering a concrete RPC protocol stack to a defined gRPC service.&lt;/p&gt;

&lt;h1&gt;
  
  
  Prerequisites
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;Basic knowledge of data structures.&lt;/li&gt;
&lt;li&gt;A working installation of Go&lt;/li&gt;
&lt;li&gt;Basic understanding of Go.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://grpc.io/docs/languages/go/quickstart/" rel="noopener noreferrer"&gt;Download&lt;/a&gt; the &lt;code&gt;.proto&lt;/code&gt;  on your machine and download the code extension for easy formatting.
# Protocol Buffers Language&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Protobuf has a minimalistic language syntax, which means protobuf also has a language type; when protobuf compiles, protobuf generates a file for a specific programming language, but in your case, you will have a &lt;code&gt;.go&lt;/code&gt; file with a struct mapping the protocol file.&lt;/p&gt;

&lt;h2&gt;
  
  
  Types  of Protocol Buffers
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Scalar value&lt;/li&gt;
&lt;li&gt;Enumeration and Repeated value&lt;/li&gt;
&lt;li&gt;Nested value&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Scalar Values
&lt;/h2&gt;

&lt;p&gt;The types used in the preceding message are scalar; these types are similar to that of Go types. These are &lt;code&gt;int&lt;/code&gt;, &lt;code&gt;int32&lt;/code&gt;, &lt;code&gt;int64&lt;/code&gt;, &lt;code&gt;string&lt;/code&gt;, and &lt;code&gt;bool&lt;/code&gt;. Below is a comparison of the type and protobuf scalar type.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Go type&lt;/th&gt;
&lt;th&gt;Protobuf type&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;float32&lt;/td&gt;
&lt;td&gt;float&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;float64&lt;/td&gt;
&lt;td&gt;double&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;uint32&lt;/td&gt;
&lt;td&gt;fixed32&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;uint64&lt;/td&gt;
&lt;td&gt;fixed64&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;[ ]byte&lt;/td&gt;
&lt;td&gt;bytes&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Default values are also given whenever the User doesn't assign a value to the scalar value. The defined scalar type will be set with a default value.&lt;/p&gt;

&lt;h2&gt;
  
  
  Enumeration and Repeated Values
&lt;/h2&gt;

&lt;p&gt;The enumeration in protobuf gives an ordering number that sets the default value order from &lt;strong&gt;zero&lt;/strong&gt; to &lt;strong&gt;n&lt;/strong&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;syntax = "proto3";
message Scheldule {
    enum month {
        janury = 0
        Febuary = 1;
        March = 2; 
        April = 3;
        May = 4;
        June = 5;
        July = 6;
        August = 7;
        September = 8;
        October = 9;
        November = 10;
        December = 11;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You possibly assigned the same value for multiple enumerations members in a situation. protobuf allows aliases to set two different members. Aliases enum looks like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum EnumAllowingAlias {
    option allow_alias = true;
    UNKNOWN = 0;
    STARTED = 1;
    RUNNING = 1;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;STARTED&lt;/code&gt; and &lt;code&gt;RUNNING&lt;/code&gt; have the same assigned value. This means both will have the same have; if you remove the duplicated value, you must remove &lt;code&gt;allow_alias&lt;/code&gt;. Otherwise, the protobuf compiler will throw an error.&lt;/p&gt;

&lt;h2&gt;
  
  
  Repeated value
&lt;/h2&gt;

&lt;p&gt;The repeated field is a protobuf's message representing a list with a given key. Repeated areas are similar to an array/list of an element. The duplicated site looks like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;message PhoneInfo{
    string serialNum = 1;
    int type = 2;
    repeated string name = 3;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The last line of code is a repeated field, an array of names. The value could be something such as this  &lt;code&gt;["100.104.112.10", "100.104.112.12"]&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Nested Field
&lt;/h2&gt;

&lt;p&gt;Protocol buffers allow a model to be nested. The inner JSON as of a member of outerJSON, and the code looks like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;message PhoneInfo {
    string serialNum = 1;
    int type = 2;
    repeated Proxy name = 3;
}
message Name {
    string serialNum = 1;
    int type = 2;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The nested field of &lt;code&gt;Name&lt;/code&gt; type into the phoneInfo.&lt;/p&gt;

&lt;p&gt;Let's look at an example of a message from the official page of the protocol buffer with a JSON:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; message person {
    option string name = 1;
    option int32 id = 2;
    option string email  = 3
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The preceding example message was defined with a type called person. The JSON type looks like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; {
    "person": {
        "name": "atanda0x",
        "id": 1,
        "email": "atandanafiu@gmail.com"
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Protocol buffers allow change support to compile with JSON style, but structures are the same. Sequential numbers (1,2,3) are given in protobuf order tags to serialize and deserialize data between two systems. The preceding file compiles the message targeted language; the GO struct and field are empty default values.&lt;/p&gt;

&lt;h2&gt;
  
  
  Protocol Buffer Compiler (protoc)
&lt;/h2&gt;

&lt;p&gt;Protocol buffer compiler uses &lt;code&gt;.proto&lt;/code&gt; to transfer data between various systems. The diagram below explains the flow of protobuf in a chosen language. In your case, it's Go.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0vbub5nkzn1dwmz8xn29.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0vbub5nkzn1dwmz8xn29.jpeg" alt="protobuf life circle"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Environment and Folder Setup
&lt;/h2&gt;

&lt;p&gt;In this section, you will set up the development evniromnet for protobuf project.&lt;/p&gt;

&lt;h2&gt;
  
  
  Initialize Project
&lt;/h2&gt;

&lt;p&gt;The first step is to initialize a new Go project. Open a new terminal and run the following command to Create a new folder: You can name it whatever you like. Mine will be &lt;code&gt;protocol-buffer&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir protocol-buffer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Next, move into that folder with the following command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd protocol-buffer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Then initialize the new Go project with the &lt;code&gt;go mod&lt;/code&gt; command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go mod init github.com/atanda0x/protobu_go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Create Folders and Server/Client Files
&lt;/h2&gt;

&lt;p&gt;Run the following command to create all the folders that will hold the project files:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir protofiles protoServer protoClient
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The command above will create three folders:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;protofiles - will contain all the protobuf files.&lt;/li&gt;
&lt;li&gt;protoServer - will contain server files&lt;/li&gt;
&lt;li&gt;protoClient - will contain client files &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Install Libraries&lt;br&gt;
You will install the necessary libraries for your project. &lt;/p&gt;

&lt;p&gt;Run the following command to install the protobuf compiler on your machine for WSL or check other os installations &lt;a href="https://grpc.io/docs/protoc-installation/" rel="noopener noreferrer"&gt;here&lt;/a&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; apt install -y protobuf-compiler
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Then you need to install &lt;strong&gt;Go proto plugins&lt;/strong&gt; using the &lt;code&gt;go get&lt;/code&gt; command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28


go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Once that’s done, create a &lt;code&gt;user.proto&lt;/code&gt;  file in the &lt;strong&gt;protofiles&lt;/strong&gt; folder in your project and add the following code inside it. This models the User's information. The example includes a few messages:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;syntax = "proto3";
package protofiles;
import "google/protobuf/timestamp.proto";
option go_package = "./";

message User {
    string name = 1;
    int32 id = 2;  // Unique ID number for this person.
    string email = 3;

    enum PhoneInfo {
      MOBILE = 0;
      HOME = 1;
      WORK = 2;
    }

    message PhoneNumber {
      string number = 1;
      PhoneInfo type = 2;
    }

    repeated PhoneNumber phones = 4;

    google.protobuf.Timestamp last_updated = 5;
}

message AddressBook {
    repeated User people = 1;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The above code declares the file as &lt;code&gt;proto3&lt;/code&gt; sytax, and a &lt;code&gt;protofiles&lt;/code&gt; package, imports the &lt;code&gt;google/protobuf/timestamp.proto&lt;/code&gt; and defiles the file the generated file should be stored—the &lt;code&gt;User&lt;/code&gt; message with fields &lt;code&gt;name&lt;/code&gt;, &lt;code&gt;id&lt;/code&gt;, and &lt;code&gt;email&lt;/code&gt;.  The phoneInfo &lt;code&gt;enums&lt;/code&gt; also have fields , the &lt;code&gt;User&lt;/code&gt; and &lt;code&gt;AddressBook&lt;/code&gt; was created as a central message with a list of User. &lt;/p&gt;

&lt;p&gt;The &lt;code&gt;package proteprofile&lt;/code&gt; tells the compiler to add the generating file about the package name. You need to compile it into a Go file, which offers Go access to the &lt;code&gt;User.proto&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;Next, you need to compile the code with this command so the protoc will generate a file that the go files will interact with:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protoc --go_out=. *.proto
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Once you run that command in the same directory, it automatically generates a &lt;code&gt;User.pb.go&lt;/code&gt; file. Please open the file; you will see that it contains a block of codes generated that looks like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpaper-attachments.dropboxusercontent.com%2Fs_F1E09B9A2063087BF8B78B46340E3A493FF2DE41CAEC7343463129C9AD2A6C6C_1688439080006_Screenshot%2B2023-07-04%2B035001.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpaper-attachments.dropboxusercontent.com%2Fs_F1E09B9A2063087BF8B78B46340E3A493FF2DE41CAEC7343463129C9AD2A6C6C_1688439080006_Screenshot%2B2023-07-04%2B035001.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The generated block of code needs to be used in the &lt;code&gt;main.go&lt;/code&gt; file to Create a protobuf string. Generating &lt;code&gt;user.pb.go&lt;/code&gt; gives you the following user types:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;An &lt;code&gt;AddressBook&lt;/code&gt; structure with a &lt;code&gt;User field&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;A &lt;code&gt;User&lt;/code&gt; structure with fields for &lt;code&gt;Name&lt;/code&gt;, &lt;code&gt;Id&lt;/code&gt;, &lt;code&gt;Email&lt;/code&gt;&lt;code&gt;,&lt;/code&gt; and &lt;code&gt;Phones&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;A &lt;code&gt;User_PhoneInfo&lt;/code&gt; structure, with fields for &lt;code&gt;Number&lt;/code&gt; and &lt;code&gt;Type&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The type &lt;code&gt;Person_PhoneType&lt;/code&gt; and a value are defined for each value in the &lt;code&gt;User.PhoneInfo&lt;/code&gt; enum.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Server and Client
&lt;/h1&gt;

&lt;p&gt;Now that the protobuf has generated a file to interact with, let’s create the server and client files. The server and client are used to interact with the generated &lt;code&gt;user.pb.go&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;Create a &lt;code&gt;server.go&lt;/code&gt; file inside your &lt;code&gt;protoServer&lt;/code&gt; folder and paste the following code.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main
import (
    "fmt"
    pb "github.com/atanda0x/protobuf-go/protofiles"
    "google.golang.org/protobuf/proto"
)
func main() {
    u := &amp;amp;pb.User{
        Id:    1234,
        Name:  "Atanda N",
        Email: "atandanafiu@gmail.com",
        Phones: []*pb.User_PhoneNumber{
            {
                Number: "+234", Type: pb.User_HOME,
            },
        },
    }
    u1 := &amp;amp;pb.User{}
    body, _ := proto.Marshal(u)
    _ = proto.Unmarshal(body, u1)
    fmt.Println("Original struct loaded from proto file:", u)
    fmt.Println("Marshaled proto data: ", body)
    fmt.Println("Unmarshaled struct: ", u1)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The code above declares  the file as a &lt;code&gt;main.go&lt;/code&gt; package,  start with &lt;code&gt;package main&lt;/code&gt;, protobuf pb were imported from the &lt;code&gt;protofile&lt;/code&gt;, imports the &lt;code&gt;proto&lt;/code&gt; package . The &lt;code&gt;struct&lt;/code&gt; mapped to the given protobuf in protofiles. The &lt;code&gt;User struct&lt;/code&gt; is used and initialized. &lt;code&gt;proto_marchal&lt;/code&gt; function serialized the &lt;code&gt;struct&lt;/code&gt;. The &lt;code&gt;marshalled&lt;/code&gt; data is not initiated because the &lt;code&gt;proto&lt;/code&gt; library serialized data into binary bytes. Protobuf in Go &lt;code&gt;struct&lt;/code&gt; generated by compiling the files, which can be used to create JSON string on the fly.&lt;/p&gt;

&lt;p&gt;You need to run/build the file with the terminal. Run the following command to do so:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go build


go run main.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You will see this output print to the terminal:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpaper-attachments.dropboxusercontent.com%2Fs_F1E09B9A2063087BF8B78B46340E3A493FF2DE41CAEC7343463129C9AD2A6C6C_1688550325259_Screenshot%2B2023-07-05%2B104347.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpaper-attachments.dropboxusercontent.com%2Fs_F1E09B9A2063087BF8B78B46340E3A493FF2DE41CAEC7343463129C9AD2A6C6C_1688550325259_Screenshot%2B2023-07-05%2B104347.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's modify this example, but you will create another file called &lt;code&gt;main_json.go&lt;/code&gt; to a different folder because using the same packages name in one directory will throw an error.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main
import (
    "encoding/json"
    "fmt"
    pb "github.com/atanda0x/protobuf-go/protofiles"
)
func main() {
    u := &amp;amp;pb.User{
        Id:    1234,
        Name:  "Atanda0x",
        Email: "atandanafiu@gmail.com",
        Phones: []*pb.User_PhoneNumber{
            {
                Number: "+23490", Type: pb.User_HOME,
            },
        },
    }
    body, _ := json.Marshal(u)
    fmt.Println(string(body))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Run the command below, and the compile will print a JSON string that can be sent to any client that understands JSON strings.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go run main_json.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpaper-attachments.dropboxusercontent.com%2Fs_F1E09B9A2063087BF8B78B46340E3A493FF2DE41CAEC7343463129C9AD2A6C6C_1688550633083_Screenshot%2B2023-07-05%2B104453.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpaper-attachments.dropboxusercontent.com%2Fs_F1E09B9A2063087BF8B78B46340E3A493FF2DE41CAEC7343463129C9AD2A6C6C_1688550633083_Screenshot%2B2023-07-05%2B104453.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Any programming language can pick JSON strings because it is easier to load data instantly.&lt;/p&gt;

&lt;p&gt;The benefit of using a protocol buffer over JSON is that buffer is intended to communicate between two backend systems with less overhead. The binary is less than text, and protocol marshalled data is smaller than JSON strings.&lt;/p&gt;

&lt;p&gt;Since protobuf is just a data format used to pass a message between two systems in the form of RPC, which makes it less important if not used in communicating, &lt;strong&gt;Google Remote Procedure Call&lt;/strong&gt; &lt;strong&gt;(gRPC)&lt;/strong&gt; takes it further to scale microservices communication, a client and server talk with each other in protocol buffer.&lt;/p&gt;

&lt;h1&gt;
  
  
  Introduction to Google Remote Procedure Call (gRPC)
&lt;/h1&gt;

&lt;p&gt;Google Remote Procedure Call(gRPC) is an open-source communication mechanism that sends/receive message between two systems. gRPC uses an architecture that supports authentication, load balancing and health checking. I wrote a &lt;a href="https://dev.to/atanda0x/a-beginners-guide-to-rpc-in-golang-understanding-the-basics-4eeb"&gt;step-by-step guide&lt;/a&gt; on how to use RPC with Go. In the article, there's a section I use JSON RPC service, which is similar to gRPC.&lt;/p&gt;

&lt;p&gt;gRPC was designed to transfer data in the form of protocol buffers. gRPC takes creation one step further(easy to use and elegant), creating APIs to define services and start running them smoothly. The combination of gRPC and protobuf is seamless since multiple programming languages can understand gRPC and protocol buffers provided data structures.&lt;/p&gt;

&lt;h2&gt;
  
  
  The advantages of gRPC over JSON, HTTP, and REST are as follows:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;gRPC uses HTTP/2 instead of traditional HTTP/1.1&lt;/li&gt;
&lt;li&gt;gRPC uses a protocol buffer over JSON/XML.&lt;/li&gt;
&lt;li&gt;The message is transmitted faster with gRPC.&lt;/li&gt;
&lt;li&gt; gRPC has a built-in control flow.&lt;/li&gt;
&lt;li&gt;gRPC supports bidirectional streaming.&lt;/li&gt;
&lt;li&gt;gRPC uses a single TCP connection for sending and receiving multiple messages between the server and the client over traditional HTTP/1.1&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm1ramvflwgyrapj4x0w8.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm1ramvflwgyrapj4x0w8.jpeg" alt="gPRC server being called by any language"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The diagram above shows that any backend system or mobile app can directly communicate with the gRPC server by firing a protobuf request.&lt;/p&gt;

&lt;h1&gt;
  
  
  Bidirectional streaming with gRPC and Protobuf in Go
&lt;/h1&gt;

&lt;p&gt;Now that you know what gRPC and Protobuf are and what they can do. Let’s create an API-based project. A client sends a money transfer request to the server in this use case. The server does a few tasks and sends those step details back to the server as a stream of responses.  &lt;/p&gt;

&lt;p&gt;The server needs to notify the client whenever some processing is performed. This is called a server push model. The server can send a stream of results back when a client asks for them only once. This is different to polling, where the client requests something each and every time. This can be useful when a series of time-taking steps need to be done. The gRPC client can escalate that job to the gRPC server. Then, the server takes its time and relays the message to the client, which reads them and does something useful. This concept is similar to Websocket but between any type of platform.  &lt;/p&gt;

&lt;p&gt;You have installed the &lt;code&gt;Go proto plugins&lt;/code&gt; in the &lt;code&gt;protobufs&lt;/code&gt; section. The Project outlook&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;serverPush
├── datafiles
│ └── transaction.proto
│ └── transaction.pb.go
│ └── transaction_grpc.pb.go
└── grpcServer
│ └── main.go
└── grpcClient
  └── main.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Create the proto file for the project with the message and service defined. Name your file &lt;code&gt;transaction.proto&lt;/code&gt; in the &lt;code&gt;protofile&lt;/code&gt; directory.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;syntax = "proto3";
package protofiles;
option go_package = "./";

message TransferRequest {
    string from = 1;
    string to = 2;
    float amount = 3;
}

message TransferResponse {
    bool confirmation = 1;
}

service MoneyTransfered {
    rpc MoneyTransfered (TransferRequest) returns (TransferResponse);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The code above has two messages and one service defined in the protocol buffer file. The exciting part is in the service; it returns a stream instead of a plain response: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    rpc MakeTransaction(TransactionRequest) returns (stream TransactionResponse) {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Compile the code with the following command below and make sure you're in the &lt;code&gt;protofiles&lt;/code&gt; directory:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protoc --go_out=. --go_opt=paths=source_relative     --go-grpc_out=. --go-grpc_opt=paths=source_relative     protofile/transaction.proto
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This creates a new file called &lt;code&gt;transaction.pb.go&lt;/code&gt; in the datafiles directory. You&lt;br&gt;
Use this file's definitions in the server and client programs, which we will create shortly. Now,  write the gRPC server code. This code is a bit different from the previous example because of the introduction of streams.&lt;/p&gt;

&lt;h2&gt;
  
  
  Creation of server and client files
&lt;/h2&gt;

&lt;p&gt;Let’s create a directory for the server and the client files. The server implements the interface that is generated from &lt;code&gt;protofile&lt;/code&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir -p grpcServer


mkdir -p grpcClient
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You &lt;code&gt;cd&lt;/code&gt; into them one after the other. In the &lt;code&gt;grpcServer&lt;/code&gt;  create a &lt;code&gt;main.go&lt;/code&gt; file.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main
import (
    "flag"
    "fmt"
    "log"
    "net"
    "time"
    pb "github.com/atanda0x/protobuf-go/StreamwithGRPC/datafiles"
    "google.golang.org/grpc"
    "google.golang.org/grpc/reflection"
)
var (
    port      = flag.Int("port", 50051, "Server port")
    noOfSteps = 3
)
type server struct {
    pb.UnimplementedMoneyTransactionServer
}
func (s *server) MakeTransaction(in *pb.TransactionRequest, stream pb.MoneyTransaction_MakeTransactionServer) error {
    log.Printf("Got request for money.....")
    log.Printf("Amount: $ %f, From A/c:%s, To A/c: %s", in.Amount, in.From, in.To)
    for i := 0; i &amp;lt; noOfSteps; i++ {
        time.Sleep(time.Second * 2)
        if err := stream.Send(&amp;amp;pb.TransactionResponse{Status: "good", Step: int32(i), Description: fmt.Sprintln("Description of step &amp;amp;d", int(i))}); err != nil {
            log.Fatalf("%v.Send(%v)  = %v", stream, "status", err)
        }
    }
    log.Printf("Successfully transfered amount $%v from %v to %v", in.Amount, in.From, in.To)
    return nil
}
func main() {
    flag.Parse()
    s := grpc.NewServer()
    lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
    if err != nil {
        log.Fatalf("Failed to listen: %v", err)
    }
    pb.RegisterMoneyTransactionServer(s, &amp;amp;server{})
    reflection.Register(s)
    if err := s.Serve(lis); err != nil {
        log.Fatalf("Failed to serve: %v", err)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The &lt;code&gt;MakeTransaction&lt;/code&gt; in the code above is the function that interests us. It takes a request and a stream as its arguments. In the function, You are looping through the number of steps (here, it is three) and performing the computation. The server is simulating the mock I/O or computation using the &lt;code&gt;time.Sleep&lt;/code&gt; function: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;stream.Send() 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This function sends a stream response from the server to the client. Now, let us compose the client program. &lt;/p&gt;

&lt;p&gt;In the generated &lt;code&gt;transaction.pb.go&lt;/code&gt; file, you will see the &lt;code&gt;RegisterMoneyTransaferedSever&lt;/code&gt; function and &lt;code&gt;MakeTransfer&lt;/code&gt; function as part of the &lt;code&gt;MoneyTransferServer&lt;/code&gt; interface. &lt;code&gt;MoneyTransfer&lt;/code&gt;has the RPC request details. It is a struct that maps to the &lt;code&gt;TransferRequest&lt;/code&gt; message defined in the protobuf file:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;rpc MakeTransfered(TransferRequest) returns (TransferResponse) {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  The Client file
&lt;/h2&gt;

&lt;p&gt;Create the client file, &lt;code&gt;cd&lt;/code&gt; into the grpcClient directory. You should have a &lt;code&gt;main.go&lt;/code&gt; file in it.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main
import (
    "context"
    "flag"
    "io"
    "log"
    pb "github.com/atanda0x/protobuf-go/StreamwithGRPC/datafiles"
    "google.golang.org/grpc"
)
var (
    address = flag.String("add", "localhost:50051", "The address to connect")
)
func ReceiveStream(client pb.MoneyTransactionClient, request *pb.TransactionRequest) {
    log.Println("Started listening to the server stream!!!!")
    stream, err := client.MakeTransaction(context.Background(), request)
    if err != nil {
        log.Fatalf("%v.MakeTransaction(_) = _, %v", client, err)
    }
    for {
        response, err := stream.Recv()
        if err == io.EOF {
            break
        }
        if err != nil {
            log.Fatalf("%v.MakeTransaction(_) = _, %v", client, err)
        }
        log.Printf("Status: %v, Operation: %v", response.Status, response.Description)
    }
}
func main() {
    flag.Parse()
    conn, err := grpc.Dial(*address, grpc.WithInsecure())
    if err != nil {
        log.Fatalf("Did not connect: %v", err)
    }
    defer conn.Close()
    client := pb.NewMoneyTransactionClient(conn)
    from := "1234"
    to := "5678"
    amount := float32(1250.75)
    ReceiveStream(client, &amp;amp;pb.TransactionRequest{From: from, To: to, Amount: amount})
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The code above &lt;code&gt;ReceiveStream&lt;/code&gt; is the custom function written to send a request and receive a stream of messages. It takes two arguments: &lt;code&gt;MoneyTransactionClient&lt;/code&gt; and &lt;code&gt;TransactionRequest&lt;/code&gt;. uses the first argument to create a stream and listens to it. The client will stop listening and terminate whenever the server exhausts all the messages. Then, an &lt;code&gt;io.EOF&lt;/code&gt; error will be returned if the client tries to receive messages. The response logging was collected from the gRPC server. The second argument, &lt;code&gt;TransactionRequest&lt;/code&gt;, is used to send the request to the server for the first time.&lt;/p&gt;

&lt;p&gt;Open a terminal to run the &lt;code&gt;grpcServer&lt;/code&gt; with the command below, run &lt;code&gt;go build&lt;/code&gt; before running the actual file.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go build 


go run main.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Open another terminal for the &lt;code&gt;grpcClient&lt;/code&gt; to run the &lt;code&gt;main.go&lt;/code&gt; file in it.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go build


go run main.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The TCP server is running on port  50051. The output of both the server and client looks like this.&lt;/p&gt;

&lt;p&gt;The client output:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpaper-attachments.dropboxusercontent.com%2Fs_F1E09B9A2063087BF8B78B46340E3A493FF2DE41CAEC7343463129C9AD2A6C6C_1689923908735_Annotation%2B2023-07-21%2B001744.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpaper-attachments.dropboxusercontent.com%2Fs_F1E09B9A2063087BF8B78B46340E3A493FF2DE41CAEC7343463129C9AD2A6C6C_1689923908735_Annotation%2B2023-07-21%2B001744.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The server gives a log message to the console at the same time.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpaper-attachments.dropboxusercontent.com%2Fs_F1E09B9A2063087BF8B78B46340E3A493FF2DE41CAEC7343463129C9AD2A6C6C_1689923924030_Annotation%2B2023-07-21%2B001804.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpaper-attachments.dropboxusercontent.com%2Fs_F1E09B9A2063087BF8B78B46340E3A493FF2DE41CAEC7343463129C9AD2A6C6C_1689923924030_Annotation%2B2023-07-21%2B001804.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The client made a request to &lt;code&gt;grpcServer&lt;/code&gt;  and passed it all from the A/C number to the A/C number and amount. The server picked up the details, processed them, and responded that everything was ok.&lt;/p&gt;

&lt;p&gt;This process happens in sync with the server. The client stays alive until all the streaming messages are sent back. The server can handle any number of clients at a given time. Every client request is considered an individual entity. This is an example of the server sending a stream of responses. Other cases can also be implemented with protocol buffers and gRPC: The client sends streamed requests to get one final response from the server The client and server are both sending streamed requests and responses at the same time.&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;And that's it! You have just built working bidirectional streaming with gRPC and protobuf. You learned the Google RPC open-source communication tool and protocol buffers, why you should use it in your project compared to other communication models, and how to generate a &lt;code&gt;pb&lt;/code&gt; file and interact with it in the client/server files. Using his advance gRPC It supports multiple programming languages and built-in features for load balancing and authentication and supports bi-directional streaming, which you build projects on. gRPC helps developers build efficient and robust distributed systems tailored to specific needs in any programing language of the developer's choice. The choice might depend on project requirements and trade-offs between building distributed systems, compatibility, and ease of use.&lt;/p&gt;

&lt;p&gt;Thank you so much for reading. Happy coding!&lt;/p&gt;

</description>
      <category>go</category>
      <category>grpc</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Beginner's Guide to RPC in Golang: Understanding the Basics</title>
      <dc:creator>atanda nafiu</dc:creator>
      <pubDate>Mon, 26 Jun 2023 08:41:27 +0000</pubDate>
      <link>https://dev.to/atanda0x/a-beginners-guide-to-rpc-in-golang-understanding-the-basics-4eeb</link>
      <guid>https://dev.to/atanda0x/a-beginners-guide-to-rpc-in-golang-understanding-the-basics-4eeb</guid>
      <description>&lt;p&gt;In the Information Exchange Model, the client sends a request, and the server responds to the client. The type of data/information exchange is based on a specific format that lets both sides communicate with each other. Presently most applications do not use this model to share but instead call services, as they would call any function. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Remote Procedure Call(RPC)&lt;/strong&gt; was intended to be the function model for networked systems. Client execute RPC like they call a native function, except client package the function parameter and send them through the network to the server. The server can then unpack this parameter and process the request, executing results to the client.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is RPC
&lt;/h2&gt;

&lt;p&gt;A Remote Procedure Call is an interprocess communication that exchanges data/information between the sender and receiver in a distributed system. RPC is used in client/server architecture for accessible communication. The primary objective of RPC is to develop the physical and logical layers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The following list is a basic overview of how the RPC process works:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The RPC client puts together the function and argument required to be sent to the server&lt;/li&gt;
&lt;li&gt;The RPC server receives them by dialling the connection&lt;/li&gt;
&lt;li&gt;The RPC server executes the remote process&lt;/li&gt;
&lt;li&gt;The RPC server responded to the client with the result&lt;/li&gt;
&lt;li&gt;The RPC client gets the response from the request duly and uses it then, it moves to the next task.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;Before getting started, ensure you have the following prerequisites:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Basic knowledge of Go&lt;/li&gt;
&lt;li&gt;Go installed on your machine&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Step 1: Setting Up Your Project
&lt;/h2&gt;

&lt;p&gt;To begin building your project, follow these steps to set up your project:&lt;/p&gt;

&lt;p&gt;Create a new directory for your project, open your terminal, and run the following command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir -p go-RPC
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This will create a new folder name &lt;code&gt;go-RPC&lt;/code&gt; in your current directory.&lt;/p&gt;

&lt;p&gt;Navigate to the project director by running the following command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd go-RPC
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now you are inside the &lt;code&gt;go-RPC&lt;/code&gt; directory. &lt;/p&gt;

&lt;p&gt;Initialize your new project by running the following command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go mod init go-RPC
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This command creates a new &lt;code&gt;go.mod&lt;/code&gt; file, your project's configuration, and the dependency management file.&lt;/p&gt;

&lt;p&gt;Following these steps, you will have a new project directory with a &lt;code&gt;go.mod&lt;/code&gt; file ready.&lt;/p&gt;

&lt;p&gt;This project will have two sub-directory; follow the steps in the preceding to create the sub-directory. You will have an RPC server and RPC client folder that looks like this.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;client-server-RPC
├── client
│    └── main.go
└── server
     └── main.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Step 2: Create The RPC Server
&lt;/h2&gt;

&lt;p&gt;You will create an RPC server to send UTC server time to the RPC client. To build the RPC server, go has two libraries, &lt;code&gt;net/rpc&lt;/code&gt; and &lt;code&gt;net/http&lt;/code&gt;.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main
import (
    "log"
    "net"
    "net/http"
    "net/rpc"
    "time"
)
type Args struct{}
type TimeServer int64
func (t *TimeServer) GiveServerTime(args *Args, reply *int64) error {
    // Fill reply pointer to send the data back
    *reply = time.Now().Unix()
    return nil
}
func main() {
    // Create a new RPC server
    timeserver := new(TimeServer)
    // Register RPC server
    rpc.Register(timeserver)
    rpc.HandleHTTP()
    // Listen for requests on port 1234
    l, e := net.Listen("tcp", ":2233")
    if e != nil {
        log.Fatal("listen error:", e)
    }
    http.Serve(l, nil)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;br&gt;
The &lt;code&gt;Args&lt;/code&gt; struct holds information about arguments passed from the client (RPC) to the server. TimeServer number to register with the &lt;code&gt;rpc.Register&lt;/code&gt;. Here, the server wishes to export an object of type TimeServer(int64). HandleHTTP registers an HTTP handler for RPC messages to DefaultServer. Then you started a TCP server that listens on port 2233—the &lt;code&gt;http.Serve&lt;/code&gt; function is used to serve it as a running program. &lt;code&gt;GiveServerTime&lt;/code&gt; is the client's function, and the current server time is returned.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Here are a few points to note:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Args struct&lt;/code&gt; has no field because the server code is not expecting any argument from the client&lt;/li&gt;
&lt;li&gt;GiveServerTime takes the Args objects and replies pointer object&lt;/li&gt;
&lt;li&gt;it sets the reply pointer object&lt;/li&gt;
&lt;li&gt;It serves on port 2233&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Step 3: Create The RPC Client
&lt;/h2&gt;

&lt;p&gt;You'll create the client to call your server and handle the response here. It also uses the same &lt;code&gt;net/rpc&lt;/code&gt; library but with a different method to dial the server.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main
import (
    "log"
    "net/rpc"
)
type Args struct {
}
func main() {
    var reply int64
    args := Args{}
    client, err := rpc.DialHTTP("tcp", "localhost"+":2233")
    if err != nil {
        log.Fatal("dialing:", err)
    }
    err = client.Call("TimeServer.GiveServerTime", args, &amp;amp;reply)
    if err != nil {
        log.Fatal("arith error:", err)
    }
    log.Printf("%d", reply)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;br&gt;
The client &lt;code&gt;DialHTTP&lt;/code&gt; to connect to the RPC server, which is running on port 2233. Call the Remote function with the Name: function format with &lt;code&gt;args&lt;/code&gt; and &lt;code&gt;reply&lt;/code&gt; with the pointer object, the client get the data collected into the reply object and call function is sequential.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; The client is running as an independent program. Both programs can be on different machines, and the computing can still be shared. This is the core concept of distributed systems. The tasks are divided and given to various RPC servers. Finally, the client collects the results and uses them for further actions. Custom RPC code is only valid when the client and server are written in Go. So to have the RPC server consumed by multiple services, we need to define the JSON RPC over HTTP. Then, any other programming language can send a JSON string and get JSON.&lt;/p&gt;

&lt;p&gt;Now you will start the &lt;code&gt;server.go&lt;/code&gt; to the program:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go run server.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Open another terminal tab to start the client.go program:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go run client.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The client console will give an output of the current UTC.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdd8v0bouyskgyloln54x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdd8v0bouyskgyloln54x.png" alt="The output of the terminal"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  JSON RPC Using Gorilla RPC
&lt;/h2&gt;

&lt;p&gt;Gorilla also provides an RPC library. It makes it easier for the client and server to be in the same file. You can send a request as JSON and receive a response as JSON. &lt;/p&gt;

&lt;p&gt;This section will be a real-world use case. You have a JSON file on the server with Twitter profile details (Name, username, followers, and following). The client requests Twitter information by making an HTTP request. When the RPC server receives the request, it reads the file from the filesystem and parses it. If the Name matches any profile, the server returns the information to the client in JSON format.&lt;/p&gt;

&lt;p&gt;You will install Gorilla RPC and Mux library with the following command: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go get github.com/gorilla/rpc


go get github.com/gorilla/mux
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Your folder structure should look like this.&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;JSON-RPC
├── go.mod
├── go.sum
├── twitterProfile.json
└── server
     └── main.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;The JSON data file&lt;/strong&gt;&lt;br&gt;
Here is a sample data file with a &lt;code&gt;twitterprofile&lt;/code&gt; details structure in it.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
    {
        "name": "Name cannot be black",
        "username": "@hackSultan",
        "followers": "187k",
        "following": "974"
    },
    {
        "name": "Scott Hanselman",
        "username": "@shanselman",
        "followers": "317k",
        "following": "10.5k"
    },
    {
        "name": "Odogwu Machalla",
        "username": "@unicodeveloper",
        "followers": "97k",
        "following": "15.5k"
    },
    {
        "name": "Gbedilodo",
        "username": "@olodocoder",
        "followers": "252",
        "following": "143"
    },
    {
        "name": "Angie Jones",
        "username": "@techgirl908",
        "followers": "114k",
        "following": "626"
    }
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Implementing The RPC JSON Server
&lt;/h2&gt;

&lt;p&gt;In this example, you must make a few changes to the preceding server example. Including Gorilla &lt;br&gt;
libraries in this example.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main
import (
    jsonparse "encoding/json"
    "io/ioutil"
    "log"
    "net/http"
    "os"
    "github.com/gorilla/mux"
    "github.com/gorilla/rpc"
    "github.com/gorilla/rpc/json"
)
// Args holds arguments passed to JSON RPC service
type Args struct {
    Name string
}
// TwitterProfie struct holds TwitterProfile JSON structure
type TwitterProfile struct {
    Name     string `json:"name,omitempty"`
    Username   string `json:"username,omitempty"`
    Followers string `json:"followers,omitempty"`
    Following string `json:"following,omitempty"`
}
type JSONServer struct{}
// TwitterProfileDetail
func (t *JSONServer) TwitterProfileDetail(r *http.Request, args *Args, reply *TwitterProfile) error {
    var twitterprofiles []TwitterProfile
    // Read JSON file and load data
    raw, readerr := ioutil.ReadFile("./twitterprofile.json")
    if readerr != nil {
        log.Println("error:", readerr)
        os.Exit(1)
    }
    // Unmarshal JSON raw data into twitterprofiles array
    marshalerr := jsonparse.Unmarshal(raw, &amp;amp;twitterprofiles)
    if marshalerr != nil {
        log.Println("error:", marshalerr)
        os.Exit(1)
    }
    // Iterate over each twitterprofile to find the given twitterprofile
    for _, twitterprofile := range twitterprofiles {
        if twitterprofile.Id == args.Id {
            // If twitterprofile found, fill reply with it
            *reply = twitterprofile
            break
        }
    }
    return nil
}
func main() {
    // Create a new RPC server
    s := rpc.NewServer() // Register the type of data requested as JSON
    s.RegisterCodec(json.NewCodec(), "application/json")
    // Register the service by creating a new JSON server
    s.RegisterService(new(JSONServer), "")
    r := mux.NewRouter()
    r.Handle("/rpc", s)
    http.ListenAndServe(":9000", r)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Open a terminal to start the server program:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go run main.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;br&gt;
The &lt;code&gt;args&lt;/code&gt; and &lt;code&gt;TwitterProfile&lt;/code&gt; structs contain information about the JSON arguments passed and the profile structure. You define a remote function called TwitterProfileDetail on a resource called &lt;code&gt;JSONServer&lt;/code&gt;. This struct is a service created to register with the RegisterService function of the RPC server. If you notice, you also write the codec as JSON. Whenever you get a request from the client, You load the JSON file called &lt;code&gt;twitterprofile.json&lt;/code&gt; into memory and then into the TwitterProfile struct using JSON's Unmarshal method. &lt;code&gt;jsonparse&lt;/code&gt; is the alias given for the Go package &lt;code&gt;encoding/json&lt;/code&gt; because the JSON package from the Gorilla import has the same Name to remove conflict, use an alias instead.&lt;/p&gt;

&lt;p&gt;In the remote function, you set the value of the reply with the matched &lt;code&gt;twiterprofile&lt;/code&gt;. The data is filled if the client's name matches any of the &lt;code&gt;twitterprofiles&lt;/code&gt; in JSON. If there is no match, the RPC server will return empty data. This way, you can create a JSON RPC to make clients universal. Here, no Go client was written. Any client can access data from the service.&lt;/p&gt;

&lt;p&gt;Now that the server is running, you must interact with the client. The client can be a CRUL command since the RPC server is serving a request over HTTP. The &lt;code&gt;twitterprofile&lt;/code&gt; name is required to get the details.&lt;/p&gt;

&lt;p&gt;Open another terminal with the following command to execute the CRUL request:&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl -X POST \&lt;br&gt;
 http: //localhost:9000/rpc \&lt;br&gt;
 -H 'cache-control: no-cache' \&lt;br&gt;
 -H 'content-type: application/json' \&lt;br&gt;
 -d '{&lt;br&gt;
    "method": "JSONServer.TwitterProfileDetail",&lt;br&gt;
    "params": [&lt;br&gt;
        {&lt;br&gt;
            "name":"Name cannot be blank"&lt;br&gt;
        }&lt;br&gt;
    ],&lt;br&gt;
    "id": "1"&lt;br&gt;
}'&lt;br&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Conclusion&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;You've learned what an RPC is and how an RPC server and client can be built. The JSON RPC is used as a use case, and the use case JSON RPC uses the Gorilla toolkit. Now you can easily create RPC in your Golang project.&lt;/p&gt;

&lt;p&gt;For a better understanding, kindly check more articles on RPC. I hope you enjoy this article. Leave a comment on the part you didn’t understand and smash the like button.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt;&lt;br&gt;
Prefer JSON RPC when multiple client technologies need to connect to your service.&lt;br&gt;
You can view the source code &lt;a href="https://github.com/atanda0x/gorilla-jsonRPC" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I'd love to connect with you on. &lt;a href="https://twitter.com/atanda0x" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt; | &lt;a href="https://www.linkedin.com/in/nafiu-atanda-7685681a7?originalSubdomain=ng" rel="noopener noreferrer"&gt;Linkedin&lt;/a&gt; | &lt;a href="https://github.com/atanda0x" rel="noopener noreferrer"&gt;Github&lt;/a&gt;&lt;/p&gt;

</description>
      <category>go</category>
      <category>rpc</category>
      <category>beginners</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Understanding the Role of Middleware in Golang</title>
      <dc:creator>atanda nafiu</dc:creator>
      <pubDate>Fri, 09 Jun 2023 20:08:36 +0000</pubDate>
      <link>https://dev.to/atanda0x/middleware-in-go-nfi</link>
      <guid>https://dev.to/atanda0x/middleware-in-go-nfi</guid>
      <description>&lt;p&gt;When building an application, a middleware is a code that hooks on the server-based request/response lifecycle, which will then chain the request from the client to the next middleware function and eventually the last function.&lt;/p&gt;

&lt;p&gt;This article thoroughly explores basic middleware chaining/multiple middlewares.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Middleware
&lt;/h2&gt;

&lt;p&gt;A middleware is an &lt;code&gt;http.handler&lt;/code&gt; that wraps another &lt;code&gt;http.handler&lt;/code&gt; in a server request/response processing. Middleware can be defined in many components; It sits between the web server and the actual handler. Whenever a handler is defined for a URL pattern, the request hits the handler and executes the business logic. All middleware process these functions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Process the request from the client before hitting the handler(authentication)&lt;/li&gt;
&lt;li&gt;Process the handler function&lt;/li&gt;
&lt;li&gt;Process the response for the client&lt;/li&gt;
&lt;li&gt;logging.. and so on&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In an application with no middleware, if a client sends a request, the request reaches the server and is handled by some function handler, and it is sent back immediately from the server to the client. But in an application with middleware, the request made by the client passes through stages like logging, authenticating, session validation, and so on, then process the business logic. It filters wrong requests from interacting with the business logic.&lt;/p&gt;

&lt;h2&gt;
  
  
  Basic Middleware
&lt;/h2&gt;

&lt;p&gt;The principle of closure function helps us write middleware. A closure function returns another function. Let's write a basic route handler with the name basicMiddleware.go&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight go"&gt;&lt;code&gt; &lt;span class="k"&gt;package&lt;/span&gt; &lt;span class="n"&gt;main&lt;/span&gt;
    &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="s"&gt;"fmt"&lt;/span&gt;
        &lt;span class="s"&gt;"net/http"&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;func&lt;/span&gt; &lt;span class="n"&gt;logic&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="n"&gt;http&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ResponseWriter&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;http&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;fmt&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Execute the logic"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Write&lt;/span&gt;&lt;span class="p"&gt;([]&lt;/span&gt;&lt;span class="kt"&gt;byte&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"OK!!!"&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;func&lt;/span&gt; &lt;span class="n"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;handlerLogic&lt;/span&gt; &lt;span class="o"&gt;:=&lt;/span&gt; &lt;span class="n"&gt;http&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;HandlerFunc&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;logic&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;http&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;middleware&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;handlerLogic&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
        &lt;span class="n"&gt;http&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ListenAndServe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;":9000"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;nil&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;func&lt;/span&gt; &lt;span class="n"&gt;middleware&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;handler&lt;/span&gt; &lt;span class="n"&gt;http&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Handler&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;http&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Handler&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;http&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;HandlerFunc&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;func&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="n"&gt;http&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ResponseWriter&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;http&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;fmt&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Middleware execution before request"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Write&lt;/span&gt;&lt;span class="p"&gt;([]&lt;/span&gt;&lt;span class="kt"&gt;byte&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Response in middleware "&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
            &lt;span class="n"&gt;handler&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ServeHTTP&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;fmt&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Middleware execution after response"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;})&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When you run the code above with &lt;code&gt;go run basicMiddleware.go&lt;/code&gt; and check &lt;code&gt;http://localhost:9000&lt;/code&gt; in your browser for this response.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Response in middleware OK!!!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The console will receive this message:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Middleware execution after response
Middleware execution before request
Execute the logic
Middleware execution after response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Explanation: The function takes in a handler and creates a wrapper to execute some operations before and after calling the handler.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The request comes on a route(middleware).&lt;/li&gt;
&lt;li&gt;The middleware handler prints &lt;code&gt;Middleware execution after response&lt;/code&gt;, writes a response, and logs the URL path.&lt;/li&gt;
&lt;li&gt;Serves the handler, which was passed an argument.&lt;/li&gt;
&lt;li&gt;Post execution, the middleware function returns back the handler function to the route.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  A Real-world Example of Middleware with Multiple and Chaining Middleware
&lt;/h2&gt;

&lt;p&gt;It is possible to chain a group of middleware with the closure logic we used in the basic. Let us create a bookstore API for saving book details; the API will have one POST method and three fields: book name, the year it was published, and the book's author. &lt;br&gt;
In a scenario, an API developer only allows JSON-type media from the client and must send the server time in  UTC back to the client for every request. Using middleware to do this. It takes two functions of middleware, which are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The first function. Check if the content type is JSON. if not, it won’t allow the request to proceed.&lt;/li&gt;
&lt;li&gt;The second function adds a Server-Time(UTC) timestamp to the response cookie.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's build our project by creating a file name bookMiddlewareAPI.go or anything you want to name.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main
import (
    "encoding/json"
    "fmt"
    "net/http"
)
type bookstore struct {
    Name   string
    Year   uint64
    Author string
}
func bookLogic(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        var book bookstore
        decoder := json.NewDecoder(r.Body)
        err := decoder.Decode(&amp;amp;book)
        if err != nil {
            panic(err)
        }
        defer r.Body.Close()
        fmt.Printf("God a book %s, that was published in %d. The author of the book is %s\n", book.Name, book.Year, book.Author)
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("201 - Created"))
    } else {
        w.WriteHeader(http.StatusMethodNotAllowed)
        w.Write([]byte("405 - Method Not Allowed"))
    }
}
func main() {
    http.HandleFunc("/bookstore", bookLogic)
    http.ListenAndServe(":9000", nil)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;You run the code above in your terminal:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;go run bookMiddlewareApi.go&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Then give a CURL request in another terminal:&lt;/strong&gt; &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; curl -H "Content-Type: application/json" -X POST http://localhost:9000/bookstore -d '{"name":"Lord of the Rings", "year": 1957, "author": "J.R.R.Tolkien"}' 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Go gives you the following:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;     God a book Lord of the Rings, and was published in 1957. The author of the book is J.R.R.Tolkien
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;CURL response will be:&lt;/strong&gt;    &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    201 - Created
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Explanation&lt;/strong&gt;: An API with a POST was created as the allowed method. it will store data in a database. JSON package was imported and used to decode the POST body given by the client. A structure was created to map the JSON body, and JSON got decoded and printed information to the console.&lt;/p&gt;

&lt;p&gt;It needs to pass a handler between multiple middleware to chain middleware together, with only one handler involved in the preceding example. and the idea is to pass the main handler to multiple middleware handlers. we’ll complete the code.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main
import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "strconv"
    "time"
)
type bookstore struct {
    Name   string
    Year   uint64
    Author string
}
func bookLogic(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        var book bookstore
        decoder := json.NewDecoder(r.Body)
        err := decoder.Decode(&amp;amp;book)
        if err != nil {
            panic(err)
        }
        defer r.Body.Close()
        fmt.Printf("God a book %s, and was published in %d. The author of the book is %s\n", book.Name, book.Year, book.Author)
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("201 - Created"))
    } else {
        w.WriteHeader(http.StatusMethodNotAllowed)
        w.Write([]byte("405 - Method Not Allowed"))
    }
}
func checkContentType(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Println("Checking the content type middleware")
        if r.Header.Get("Content-Type") != "application/json" {
            w.WriteHeader(http.StatusUnsupportedMediaType)
            w.Write([]byte("415 - Unsupported Media Type, Please send a JSON"))
            return
        }
        handler.ServeHTTP(w, r)
    })
}
func cookieTimer(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        handler.ServeHTTP(w, r)
        cookies := http.Cookie{Name: "Server-Time(UTC)", Value: strconv.FormatInt(time.Now().Unix(), 10)}
        http.SetCookie(w, &amp;amp;cookies)
        log.Println("Currently in the set server time middleware")
    })
}
func main() {
    bookLogicHandler := http.HandlerFunc(bookLogic)
    http.Handle("/bookstore", checkContentType(cookieTimer(bookLogicHandler)))
    http.ListenAndServe(":9000", nil)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;You run the code above in your terminal:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go run bookMiddlewareApi.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Then give a CURL request in another terminal: &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; curl -i -H "Content-Type: application/json" -X POST http://localhost:9000/bookstore -d '{"name":"Lord of the Rings", "year": 1957, "author": "J.R.R.Tolkien"}' 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;The output looks like this:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    HTTP/1.1 200 OK
    Date: Tue, 06 Jun 2023 21:56:51 GMT
    Content-Length: 13
    Content-Type: text/plain; charset=utf-8

    201 - Created
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;If we remove the &lt;code&gt;Content-Type:application/json&lt;/code&gt; from the CURL command, middleware blocks us from executing the main handler:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl -i -X POST http://localhost:9000/bookstore -d '{"name":"Lord of the Rings", "year": 1957, "author": "J.R.R.Tolkien"}'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output looks like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    HTTP/1.1 415 Unsupported Media Type
    Date: Tue, 06 Jun 2023 22:00:11 GMT
    Content-Length: 46
    Content-Type: text/plain; charset=utf-8

    415 - Unsupported Media Type, Please send a JSON
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Cookies will be set from the other middleware.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt; checkContentType is the first middleware we added to the preceded code; it checks the content type request and allows or blocks the request from going further. The cookieTimer is the second middleware we added; it was designed to add a cookie to the response with a value of the time in the UNIX epoch. The form  of chaining middleware we did is readable for two to three middleware:&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {&lt;br&gt;
    bookLogicHandler := http.HandlerFunc(bookLogic)&lt;br&gt;
    http.Handle("/bookstore", checkContentType(cookieTimer(bookLogicHandler)))&lt;br&gt;
    http.ListenAndServe(":9000", nil)&lt;br&gt;
}&lt;br&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Conclusion&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;This article discussed some essential aspects of building web applications with Go. It is important for a Go developer to know middleware and how to use it. I hope you’ve learned a lot from this article. Feel free to leave a comment on what is not clear to you.&lt;/p&gt;

</description>
      <category>go</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>http</category>
    </item>
    <item>
      <title>REST API Best Practice: Understanding Verbs and status code</title>
      <dc:creator>atanda nafiu</dc:creator>
      <pubDate>Thu, 01 Jun 2023 11:18:45 +0000</pubDate>
      <link>https://dev.to/atanda0x/rest-api-best-practice-understanding-verbs-and-status-code-fei</link>
      <guid>https://dev.to/atanda0x/rest-api-best-practice-understanding-verbs-and-status-code-fei</guid>
      <description>&lt;p&gt;Software developers have been working with REST architecture through HTTP and APIs. API isn't just an ordinary interface that you use to interact with the third-party program, communication between programs is done wrongly all because developers use the wrong HTTP status code to express responses. It is more difficult when exposing APIs that clients use to interact with applications in most modern web applications.&lt;/p&gt;

&lt;p&gt;In this article, we'll explore in detail the most used REST verbs, the concept of CROS(Cross-Origin Resources Sharing), HTTP status code, and single-page applications with the REST API.&lt;/p&gt;

&lt;h2&gt;
  
  
  Table of Contents
&lt;/h2&gt;



&lt;ul&gt;
&lt;li&gt;
The REST Web Verbs

&lt;ul&gt;
&lt;li&gt;REST API Verbs&lt;/li&gt;
&lt;li&gt;Path parameters vs Query parameters&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;Cross-Origin Resources Sharing(CROS)&lt;/li&gt;

&lt;li&gt;HTTP Status Code&lt;/li&gt;

&lt;li&gt;

REST API With Single Page Application(SPA)

&lt;ul&gt;
&lt;li&gt;The Old way of data flow in SPA&lt;/li&gt;
&lt;li&gt;The Modern Way of Data Flow in SPA Through REST &lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;Conclusion&lt;/li&gt;

&lt;/ul&gt;



&lt;h2&gt;
  
  
  The REST Web Verbs
&lt;/h2&gt;

&lt;p&gt;The information that should be sent when a request is made by the client must include the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;REST verbs&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Header Information&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Body(optional)&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As a software engineer, you will work with these six REST verbs most of the time. The table below explains the operation, target resources, and what happens if a request fail or succeeds.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2fulszmecbfylomalqo5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2fulszmecbfylomalqo5.png" alt="REST verbs and its resources "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Since REST is stateless, the client should find a way to know if the operation was successful or failed. In this case, HTTP has a status code for responses. REST API strictly follow its rule to achieve client-server communication return.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;http://HostName/API/endpoint/Query(optonal)&lt;/code&gt;&lt;br&gt;
A well-defined REST service has the format above, which consists of the host and API endpoint&lt;/p&gt;

&lt;h3&gt;
  
  
  REST API Verbs
&lt;/h3&gt;

&lt;p&gt;The REST API design start with the operation definition and the API endpoints the design document should list all the available endpoints for the given resources before implementing the API. To understand the REST verbs we should carefully observe the REST endpoints with examples.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GET&lt;/strong&gt;&lt;br&gt;
All the browsing on the web is done by performing a GET request to the website server which means GET fetches given resources from the server. A successful GET operation returns an OK (200 status code). GET uses two types of URL queries &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Path-based parameter&lt;/strong&gt; &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Query parameter&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Path parameters are request parameters attached to a URL that is to a specific rest of API resources. For example, PayPal creates a billing agreement with companies around the world, when a client registers with PayPal for a payment system, they provide a REST API for all the client billing needs and nd, and its GET request for billing looks like this:&lt;br&gt;
&lt;code&gt;/v2/payments/billings-agreements/agreement_Id&lt;/code&gt;&lt;br&gt;
when the server sees it, and interprets it as &lt;em&gt;I got an HTTP request for an agreement_Id from the billing agreement&lt;/em&gt;. If the request is on the database, it responds to 200 else it sends not-found 400&lt;/p&gt;

&lt;p&gt;Query added detailed information to its resources from the server. for example, a movie API fetch, create and update the details of the movie. Query Get request format look like:&lt;br&gt;
 &lt;code&gt;/v2/movies/?category=action&amp;amp;released_date=2023&lt;/code&gt;&lt;br&gt;
The URL above has a query parameter requesting details from movie resources that satisfied the following conditions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;It should be an Action movie&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The movie should have been released in the year 2023&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Path parameters vs Query parameters
&lt;/h3&gt;

&lt;p&gt;Query parameters are used to fetch multiple resources based on query parameters but if a client needs a single resource with specific URL information, it is best advised to use path-based parameters to specify the resources.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;POST&lt;/strong&gt; &lt;br&gt;
post method is used to create new resources on the server. A successful post-operation returns a 201 status code. we'll use examples of previous movie creation, post request update multiple resources: &lt;code&gt;/v2/movies&lt;/code&gt;.&lt;br&gt;
The POST request json body looks like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 JSON
{"name": "The woman king", "year": 2023, "Director ": "atanda0x"}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This creates a new movie in the database, it has an "id" assigned to the record so when GET calls the resources, the URL is created, and the post is done only once. Note that we entered the incorrect release year, in other to update the resources we use the PUT request&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PUT&lt;/strong&gt;&lt;br&gt;
The put method is similar to that of the post method. it is used to replace the resources that already exist in the database. The main difference between the is idempotent, POST call creates two instances with the same data but PUT update a single resource that already exists:&lt;br&gt;
&lt;code&gt;/v2/movie/4289&lt;/code&gt;&lt;br&gt;
 with a JSON body that looks like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 JSON 
{"name": "The woman king", "year": 2022, "Director ": "atanda0x"}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The movie id is 4289. it updates the movie by "year:2022". PUT has a drawback which it updates the entire movie resources with the new one, and this is bad for a reason, the PATCH fixes this.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PATCH&lt;/strong&gt; &lt;br&gt;
PATCH came into play with the little setback of the PUT. It's similar to PUT except it won't replace the whole record with a new one. Since we need to change a column as the name implies it patches the column that is being modified: &lt;code&gt;/v2/movies/4289&lt;/code&gt;&lt;br&gt;
it JSON body looks like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
 JSON
{"ISBN":  "13337646743"}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;It tells the server, to search for the book with Id 4289, and modify this column with the given value. Both PUT and PATCH return a 200 status code for success and a 404 for not-found.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DELETE&lt;/strong&gt;&lt;br&gt;
The DELETE method is used to delete resources that are no longer needed from the database. It has some similarities to PUT but without a body. It only needs an Id of the resources to be deleted, since the resources are deleted any GET request call from a client returns a 404 not-found.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;OPTION&lt;/strong&gt;&lt;br&gt;
The OPTIONS method is not mostly used in all other API development. Given that it tries to know all available methods define in the server. We can describe it as a menu card in a restaurant, and then ordering available items. It is best practice to implement the OPTIONS method on the server.&lt;/p&gt;

&lt;h2&gt;
  
  
  Cross-Origin Resources Sharing(CROS)
&lt;/h2&gt;

&lt;p&gt;The OPTIONS method led to cross-origin resource sharing. CROS is a protocol that enables controlled access to resources from any origin (schema, domain, port) other than its own from which a browser need to permit the loading of resources. Initially, browser security prevents clients from making a cross-origin request that is when a site loaded with a URL &lt;em&gt;xyz.com&lt;/em&gt; can only make an API call to its host, and if a client need to request data from another URL &lt;em&gt;abc.com&lt;/em&gt;, the second server should have a mechanism to recognize &lt;em&gt;xyz.com&lt;/em&gt; to get its resources. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0xu97jhw53dfrjtrqyq1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0xu97jhw53dfrjtrqyq1.png" alt="Cross-Origin Resources Sharing "&gt;&lt;/a&gt;&lt;br&gt;
This logic explains the image above. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;em&gt;xyz.com&lt;/em&gt; request OPTION method on the &lt;em&gt;abc.com&lt;/em&gt; server&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;abc.com&lt;/em&gt; send a header: &lt;strong&gt;Access-control-Allow origin&lt;/strong&gt;: &lt;code&gt;http://xyz.com&lt;/code&gt; in response to the client&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;xyz.com&lt;/em&gt; can access the resources on &lt;em&gt;abc.com&lt;/em&gt; without restriction that calls the REST method&lt;/li&gt;
&lt;li&gt;In some cases &lt;em&gt;abc.com&lt;/em&gt; may feel like giving all its resources to any host after one initial request which it set access to * which means to any.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  HTTP Status Code
&lt;/h2&gt;

&lt;p&gt;HTTP works with &lt;strong&gt;Request &amp;amp; Response Model&lt;/strong&gt; whenever a request is sent a response with a status code is received through this model. There are a few families of HTTP status codes, each family has different status and meaning. We concentrate on the most common families, which range from &lt;strong&gt;100&lt;/strong&gt; to &lt;strong&gt;500&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1xx family(Informational)&lt;/strong&gt;&lt;br&gt;
Communicates transfer, protocol-level information family. They indicate that the server has received the request and is continuing the process. This family code is purely temporary and is given while the request processing continues. &lt;strong&gt;100, 101, 102,&lt;/strong&gt; and &lt;strong&gt;103&lt;/strong&gt; fall under this family. A client doesn't encounter these much, as it's not the final request response.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;100(Continue Operation)&lt;/strong&gt; is an initial part of the request that has been received by the server and the client can proceed or ignore the response if the request has already finished.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;102(Processing Operation)&lt;/strong&gt; is returned when the server has accepted the full request but has not yet completed it, and the response is not available yet.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;103(Early Hints)&lt;/strong&gt; was intended to be used to allow a client to preload resources, while the server prepares a response. Like a primary user with the link header.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2xx family (successful)&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;200&lt;/strong&gt; and &lt;strong&gt;201&lt;/strong&gt; fall under the success family. They indicate that an operation was successful. Plain &lt;strong&gt;200 (Operation Successful)&lt;/strong&gt; is a successful CRUD Operation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;200 (Successful Operation)&lt;/strong&gt; is the most common type of response status code in REST.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;201 (Successfully Created)&lt;/strong&gt;is returned when a POST operation successfully creates a resource on the server&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;204 (No content)&lt;/strong&gt; is issued when a client needs a status but does not have any data back.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;205(Reset Content)&lt;/strong&gt; is issued that the client should reset the document that this request.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;206(Partial Content)&lt;/strong&gt; is a response to a &lt;strong&gt;Range&lt;/strong&gt; header sent from the client when requesting only a part of the resource.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;226(IM response)&lt;/strong&gt; is issued when the server has successfully fulfilled a &lt;strong&gt;GET&lt;/strong&gt; request for a resource, and the response is a representation of the result of one or multiple instances applied to the current instance.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;3xx family (redirection)&lt;/strong&gt;&lt;br&gt;
These status codes are used to convey redirection messages. The most important ones are &lt;strong&gt;301&lt;/strong&gt; and &lt;strong&gt;304&lt;/strong&gt;: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;301(Moved Permanently)&lt;/strong&gt; is issued when a resource is moved permanently to a new URL endpoint. It is essential when an old API is deprecated. It returns the new endpoint in the response with the &lt;strong&gt;301&lt;/strong&gt; status. By seeing that, the client should use the new URL in response to achieving its target.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;304(Not Modified)&lt;/strong&gt; status code indicates that content is cached and no modification happened for the resource on the server. This helps in caching content at the client and only requests data when the cache is modified.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;4xx family (client error)&lt;/strong&gt;&lt;br&gt;
These are the standard error status codes that the client needs to interpret and handle further actions. These have nothing to do with the server. A wrong request format or ill-formed REST method can cause these errors. Of these, the most frequent status code API developers use are &lt;strong&gt;400, 401, 403, 404, and 405&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;400 (Bad Request)&lt;/strong&gt; is returned when the server cannot understand the client's request.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;401 (Unauthorized)&lt;/strong&gt; is returned when the client is not sending the authorization information in the header.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;403 (Forbidden)&lt;/strong&gt; is returned when the client has no access to a certain type of resource.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;404 (Not Found)&lt;/strong&gt; is returned when the client request is on a resource that is nonexisting.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;405 (Method Not Allowed)&lt;/strong&gt; is returned if the server bans a few methods on resources. GET and HEAD are exceptions.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;5xx family (server error)&lt;/strong&gt;&lt;br&gt;
These are the errors from the server. The client request may be perfect, but due to a bug in the server code, these errors can arise. The commonly used status codes are &lt;strong&gt;500, 501, 502, 503,&lt;/strong&gt; and &lt;strong&gt;504&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;500 (Internal Server Error)&lt;/strong&gt; status code gives the development error which is caused by some buggy code or some unexpected condition.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;501 (Not Implemented)&lt;/strong&gt; is returned when the server is no longer supporting the method on a resource.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;502 (Bad Gateway)&lt;/strong&gt; is returned when the server itself got an error response from another service vendor.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;503 (Service Unavailable)&lt;/strong&gt; is returned when the server is down due to multiple reasons, like a heavy load or maintenance.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;504 (Gateway Timeout)&lt;/strong&gt; is returned when the server is waiting a long time for a response from another vendor and is taking too much time to serve the client.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  REST API With Single Page Application(SPA)
&lt;/h2&gt;

&lt;p&gt;Instead of building with the traditional UI way(request web page), SPA makes the building of UI a different way. There are many frameworks with the likes of Reactjs, Vuejs, Angulajs, and so on used to develop web page UIs rapidly and pretty simple. All frameworks help to implement one design pattern that is not requesting the web page but only REST API. Frontend is considered a separate entity that needs to talk to the backend only using REST API can achieve this. There are two ways data flow in SPA&lt;/p&gt;

&lt;h3&gt;
  
  
  The Old way of data flow in SPA
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffqkvvtzasaka2eq3oj00.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffqkvvtzasaka2eq3oj00.png" alt="Old data flow in SPA"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Request a web page from the server&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Authenticate and show the dashboard UI&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Allow the user to modify and save &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Request as many web pages from the server as needed to show individual pages.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  The Modern Way of Data Flow in SPA Through REST
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff7pui66cfy7gvh359h9m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff7pui66cfy7gvh359h9m.png" alt="modern way data flow in SPA"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Request the HTML template to the browser in one single go.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Query the JSON REST API to fill a model(data object)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It adjusts the UI according to the data in the model(JSON)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When a user modifies the UI, the model(data object) should change automatically. &lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Communication happens only in the form of the RET API, the client takes care of the logical representation of data. It causes The system to move from &lt;strong&gt;Response Oriented Architecture(ROA)&lt;/strong&gt; to &lt;strong&gt;Service Oriented Architecture (SOA)&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;I hope you get to learn from this article teaches you about REST API, HTTP status code, REST verbs, and building with SPA. It's a long read, and I hope you find it worth it. &lt;/p&gt;

&lt;p&gt;Kindly share your suggestion and comments, feedback in the comment section below.&lt;/p&gt;

&lt;p&gt;You can also learn more about REST API on different platforms on the web browser.&lt;/p&gt;

</description>
      <category>http</category>
      <category>rest</category>
      <category>webdev</category>
      <category>api</category>
    </item>
    <item>
      <title>Web Services</title>
      <dc:creator>atanda nafiu</dc:creator>
      <pubDate>Wed, 17 May 2023 16:57:25 +0000</pubDate>
      <link>https://dev.to/atanda0x/understanding-web-services-1d70</link>
      <guid>https://dev.to/atanda0x/understanding-web-services-1d70</guid>
      <description>&lt;p&gt;Testing and processes in web service are still much more complex with advancements in technology. The tech giants have raised the bar by addressing the need for application development, and its scale from the likes of Amazon, Google, Facebook, and Microsoft is exactly what makes web services possible. &lt;/p&gt;

&lt;p&gt;Understanding how web service works, and what it takes to bring these processes to life. You will get to know in this article.&lt;/p&gt;

&lt;h2&gt;
  
  
  Table of Contents
&lt;/h2&gt;



&lt;ul&gt;
&lt;li&gt;What are web services&lt;/li&gt;
&lt;li&gt;How The Web Service Works&lt;/li&gt;
&lt;li&gt;Different Types of Web Services &lt;/li&gt;
&lt;li&gt;SOAP(Simple Object Access Protocol)&lt;/li&gt;
&lt;li&gt;REST(Representational State Transfer)&lt;/li&gt;
&lt;li&gt;WSDL(Web Service Description Language)&lt;/li&gt;
&lt;li&gt;The Difference Between Web Services and Web API&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ul&gt;



&lt;h2&gt;
  
  
  What are web services
&lt;/h2&gt;

&lt;p&gt;A web service is a service software that is available on the internet either private or public networks, which uses a standardized messaging protocol to communicate with different computer systems. It makes peer-to-peer communication easier and not platform specific. The web service uses a standardized XML messaging system and JSON to transfer machine-processable file format through HTTP.&lt;/p&gt;

&lt;h2&gt;
  
  
  How The Web Service Works
&lt;/h2&gt;

&lt;p&gt;A client invokes a series of web services by sending an XML message(request) to the server and then waiting for a corresponding response in the same format which hosts the web services. These requests are made possible through RPC(Remote Procedure Calls), RPC calls to methods are hosted by a web service. For example, Google provides a cloud platform that runs apps, host site, and store data via cloud.google.com. The programming language with the likes of Golang, Python, and more would have the ability to communicate with the web service.&lt;br&gt;
It is more like a road between two endpoints where messages are transferred smoothly, and two individual programmable entities communicate with each other through API(Application programmable interface).&lt;/p&gt;

&lt;h2&gt;
  
  
  Different Types of Web Services
&lt;/h2&gt;

&lt;p&gt;These are prominent ones that have evolved:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;UDDI(Universal Description Discovery and Integration):&lt;/strong&gt; UDDI is an XML-based(Extensible Markup Language) standard for publishing, detailing, and recovery of information about web services. It's mainly an internal registry for businesses globally. This includes XML schema for SOAP messages that define a set of documents to describe the business and service information. Before you can publish your business entity and web service to a public registry, you must first register the business entity with a UDDI registry. UDDI registries come in two forms, public and private registries. Both comply with the same specifications. A public registry is a collection of peer directories that contain information about businesses and services, while a private registry enables you to publish and test your internal business application in a secure, private environment.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;XML-RPC(Remote procedure call):&lt;/strong&gt;&lt;br&gt;
XML-RPC is one of the simplest and foolproof XML protocols to exchange data between a wide variety of devices on a network. It's a remote procedure call that uses HTTP as the transport and XML as the encoding. Rpc gives developers a mechanism for defining interfaces that can be called over a network. The interface can be as simple as a function call or as complex as a large API.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SOAP(Simple Object Access Protocol):&lt;/strong&gt;&lt;br&gt;
SOAP is an XML-based protocol for accessing data and documents over HTTP or SMTP(Simple Mail Transfer Protocol). It has some specifications that could be used across all applications. Exchanging data between applications is crucial in today's world, but data exchange between these heterogeneous applications would be complex. SOAP was designed to work with XML over HTTP and has some sort of specification that could be used across all applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;REST(Representational State Transfer):&lt;/strong&gt;&lt;br&gt;
REST is a web standard-based architecture that uses HTTP protocol. It defines a set of methods to build a web API (Application Programming Interface) due to its simplicity and client fondly nature. The main benefit of REST is statelessness, which means does not store any information about the client, instead, every request contains information for the server to process its request. &lt;br&gt;
Objects in REST are always manipulated from the URL(Uniform Resources Identifier)/IDs and payloads are used to send and return information that is too large to be handled as a parameter. The payload is of a variety of different forms including XML, JSON, and HTML.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;WSDL(Web Service Description Language):&lt;/strong&gt; WDDI Is an XML-based interface description language that tells the client application the functionality offered by a web service. WSDL description of a web service that provides a machine-processable description of how the service can be called structure to return parameters it's expected. It specifies the method of the service and the location of the service with the following elements types, messages, port type, and binding.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Difference Between Web Services and Web API
&lt;/h2&gt;

&lt;p&gt;Both web service and web API are modern software architectures, that are mistaken for each other which makes it difficult to distinguish.&lt;br&gt;
We talked about web services at the beginning of this article.&lt;br&gt;
A web API is a protocol that allows applications to communicate with different applications that can be exposed through local files, such as (.H file in C/C++ program and .go in Golang to allow two local application)ons to communicate with each other and it doesn't require a network to communicate with a single device.&lt;br&gt;
With the explanation above it comes down to that a web service is a protocol and standard use for exchanging data between systems or applications, it must be accessed through the internet, whereas web API is a software interface that allows two applications to interact with each other over the Internet.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Web services and web API makes the Internet more accessible than ever before through different medium, with the help of tech giants companies advancing the web service and more accessible over the Internet, though it's still complex. But is rapidly growing over time.&lt;/p&gt;

&lt;p&gt;If you're looking to improve your knowledge or you want to explore web services it is advised you dive in and enjoy the world of web services.&lt;/p&gt;

</description>
      <category>backend</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
