<?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: Parth Shukla</title>
    <description>The latest articles on DEV Community by Parth Shukla (@parthshukla).</description>
    <link>https://dev.to/parthshukla</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%2F731741%2Fca18b0a6-763b-4e18-87c5-de5e623e0100.jpg</url>
      <title>DEV Community: Parth Shukla</title>
      <link>https://dev.to/parthshukla</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/parthshukla"/>
    <language>en</language>
    <item>
      <title>Cache Interceptor in Angular</title>
      <dc:creator>Parth Shukla</dc:creator>
      <pubDate>Sun, 04 Sep 2022 15:33:03 +0000</pubDate>
      <link>https://dev.to/parthshukla/cache-interceptor-in-angular-555c</link>
      <guid>https://dev.to/parthshukla/cache-interceptor-in-angular-555c</guid>
      <description>&lt;p&gt;In previous blog we have explained what are Interceptors in Angular and gave example of an basic auth interceptor,&lt;br&gt;
In this one we are going to learn how add multiple Interceptors and what are catching Interceptors.&lt;/p&gt;

&lt;p&gt;Please have a quick read of the first blog for context,&lt;/p&gt;

&lt;p&gt;Now in order to add multiple Interceptors, we first add them in root module file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';
...

@NgModule({
  ...
  imports: [
    ... ,
    HttpClientModule
  ],
  providers: [
    ... ,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: InterceptorOne,
      multi: true,
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: InterceptorTwo,
      multi: true,
    }
  ],
  ...
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt; : InterceptorOne and InterceptorTwo are just examples and you have to add your own interceptor class instead of it.&lt;/p&gt;

&lt;p&gt;Now we implement our caching Interceptor &lt;/p&gt;

&lt;p&gt;This interceptor caches the request only when the headers contains cacheRequest parameter to true.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { CacheService } from './cache.service';

@Injectable()
export class CachingInterceptor implements HttpInterceptor {

  constructor(private readonly cacheService: CacheService) {
  }

  intercept(req: HttpRequest&amp;lt;any&amp;gt;, next: HttpHandler): Observable&amp;lt;HttpEvent&amp;lt;any&amp;gt;&amp;gt; {
    // Don't cache if it's not a GET request
    if (req.method !== 'GET') {
      return next.handle(req);
    }

    // delete cache if no header is set by service's method
    if (!req.headers.get('cacheRequest')) {
      if (this.cacheService.cacheMap.get(req.urlWithParams)) {
        this.cacheService.cacheMap.delete(req.urlWithParams);
      }

      return next.handle(req);
    }

    // Checked if there is cached data for this URI
    const cachedResponse = this.cacheService.getFromCache(req);
    if (cachedResponse) {
      // In case of parallel requests to same URI,
      // return the request already in progress
      // otherwise return the last cached data
      return (cachedResponse instanceof Observable) ? cachedResponse : of(cachedResponse.clone());
    }

    // If the request of going through for first time
    // then let the request proceed and cache the response
    return next.handle(req)
        .pipe(tap(event =&amp;gt; {
            if (event instanceof HttpResponse) {
                this.cacheService.addToCache(req, event);
            }
        }));
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Cache Service&lt;/strong&gt; : To store and retrieve for caches&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class CacheService  {
  cacheMap = new Map&amp;lt;any, any&amp;gt;(null);

  getFromCache(req: HttpRequest&amp;lt;any&amp;gt;): HttpResponse&amp;lt;any&amp;gt; | undefined {
    const url = req.urlWithParams;
    const cached = this.cacheMap.get(url);

    if (!cached) {
      return undefined;
    }

    return (this.cacheMap.get(url)).response;
  }

  addToCache(req: HttpRequest&amp;lt;any&amp;gt;, response: HttpResponse&amp;lt;any&amp;gt;): void {
    const url = req.urlWithParams;
    const entry = { url, response, addedTime: Date.now() };
    this.cacheMap.set(url, entry);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Sample Get request&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getMethod(int param1, cache = false): any {
    let headers: HttpHeaders;
    if (cache) {
      headers = new HttpHeaders({ 'cacheRequest': 'true' });
    }

    return this.http.get(
      'http://apiUrl',
      { headers }
    );
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Spring Boot Actuators</title>
      <dc:creator>Parth Shukla</dc:creator>
      <pubDate>Sun, 04 Sep 2022 14:44:22 +0000</pubDate>
      <link>https://dev.to/parthshukla/spring-boot-actuators-5b9</link>
      <guid>https://dev.to/parthshukla/spring-boot-actuators-5b9</guid>
      <description>&lt;p&gt;Spring boot actuator feature can be used to publish the application details, metrics, etc. that we can use to monitor the application easily.&lt;/p&gt;

&lt;p&gt;We can use the actuator starter dependency to enable the actuator feature.&lt;/p&gt;

&lt;p&gt;The below snippet shows the maven dependency.&lt;/p&gt;

&lt;p&gt;Adding this dependency will autoconfigure the required configuration in the application and also enables the default actuator endpoints and health indicators.&lt;/p&gt;

&lt;p&gt;     org.springframework.boot&lt;br&gt;
        spring-boot-starter-actuator&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Actuator Endpoint&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Just by adding the actuator dependency, our application now has a lot of information exposed that would be very handy for debugging or general microservice insight.&lt;/p&gt;

&lt;p&gt;Most endpoints are sensitive – meaning they’re not fully public – while a handful is not: /health and /info.&lt;/p&gt;

&lt;p&gt;Description of Few Endpoints:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;/health: Exposes the application health status.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;/beans: Exposes the configured spring beans in the application context. Provides details like the scope of the bean, bean type, etc.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;/caches: Exposes available caches in the application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;/env: Provides all available environment configuration property details.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;/configprops: Exposes all available configuration classes list.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;/mappings: Exposes all availabe HTTP request mapping details in the application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;/metrics: Exposes application metrics like JVM metrics, system metrics, and also the tomcat server metrics, etc.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;/heapdump: Provides the application heap dump.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;/threaddump: Exposes the thread information.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;/loggers: Exposes the logging application configuration information like log level, etc.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;/logfile: For web applications, this endpoint returns the logfile content. We can also retrieve only a part of the log file.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;/shutdown: We can use this endpoint to gracefully shut down the spring boot application. This is disabled by default.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Include or exclude actuator endpoints&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#To include all the default web endpoints:
management.endpoints.web.exposure.include=*

#To include specific web endpoints:
management.endpoints.web.exposure.include=health,info

#To exclude specific web endpoints:
management.endpoints.web.exposure.exclude=beans

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;changing the actuator http management port&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;management.server.port=9080
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Creating Custom Actuator Endpoint&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.actuatorsample;

import java.util.HashMap;
import java.util.Map; 
import org.springframework.boot.actuate.endpoint.annotation.DeleteOperation;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import org.springframework.stereotype.Component;

@Component
@Endpoint(id = "sampleEndpoint")
public class CustomActuator {

    @ReadOperation
    public Map&amp;lt;String, String&amp;gt; readEndpoint() {
        Map&amp;lt;String, String&amp;gt; map = new HashMap&amp;lt;&amp;gt;();
        map.put("readMessage", "This is our sample actuator endpoint.!!");
        return map;
    }

    @WriteOperation
    public Map&amp;lt;String, String&amp;gt; writeEndpoint(String value) {

        Map&amp;lt;String, String&amp;gt; map = new HashMap&amp;lt;&amp;gt;();
        map.put("writeMessage", "This is sample actuator write endpoint.!!" + value);
        return map;
    }

    @DeleteOperation
    public Map&amp;lt;String, String&amp;gt; deleteEndpoint() {
        Map&amp;lt;String, String&amp;gt; map = new HashMap&amp;lt;&amp;gt;();
        map.put("readMessage", "This is sample actuator delete endpoint.!!");
        return map;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Interceptors in Angular (Authentication, Caching, Logging, Error Handling)</title>
      <dc:creator>Parth Shukla</dc:creator>
      <pubDate>Wed, 31 Aug 2022 10:23:20 +0000</pubDate>
      <link>https://dev.to/parthshukla/interceptors-in-angular-authentication-caching-logging-error-handling-13j4</link>
      <guid>https://dev.to/parthshukla/interceptors-in-angular-authentication-caching-logging-error-handling-13j4</guid>
      <description>&lt;p&gt;Angular interceptors are merely a special kind of HTTP client service that has the sole purpose of intercepting every HTTP request performed. This is true for both incoming and outgoing HTTP requests. OK, I’ve seen this quick definition in several places, but what does that exactly mean? How does it work?&lt;/p&gt;

&lt;p&gt;When the response arrives from the back end the Interceptors can transform it before passing it to our application.&lt;/p&gt;

&lt;p&gt;One of the main benefits of the Http Interceptors is to add the Authorization Header to every request. We could do this manually, but that is a lot of work and error-prone. Another benefit is to catch the errors generated by the request and log them.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Creating an HTTP Interceptor&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We create an Injectable service that implements &lt;strong&gt;HttpInterceptor&lt;/strong&gt; interface and thus must implement method &lt;strong&gt;Intercept&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
@Injectable() export class DemoHttpInterceptor implements HttpInterceptor {
 intercept(req: HttpRequest&amp;lt;any&amp;gt;, next: HttpHandler): Observable&amp;lt;HttpEvent&amp;lt;any&amp;gt;&amp;gt; {
    //do whatever you want with the HttpRequest
    return next.handle(req);
}

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

&lt;/div&gt;



&lt;p&gt;Then add the class in Root Module&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useClass: DemoHttpInterceptor,
        multi: true
    }
],

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Basic Auth Example using Http Interceptor&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { AuthState } from '../../store/auth.state';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private authService: AuthService) {}

  intercept(request: HttpRequest&amp;lt;any&amp;gt;, next: HttpHandler): Observable&amp;lt;HttpEvent&amp;lt;any&amp;gt;&amp;gt; {
    return next.handle(this.addAuthToken(request));
  }

  addAuthToken(request: HttpRequest&amp;lt;any&amp;gt;) {
    const token = this.authService.getAuthToken();

    return request.clone({
        setHeaders: {
          Authorization: `Basic ${token}`
        }
    })
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Observables in Angular</title>
      <dc:creator>Parth Shukla</dc:creator>
      <pubDate>Sun, 21 Aug 2022 19:17:00 +0000</pubDate>
      <link>https://dev.to/parthshukla/observables-in-angular-bno</link>
      <guid>https://dev.to/parthshukla/observables-in-angular-bno</guid>
      <description>&lt;p&gt;&lt;strong&gt;Observable in Angular is a feature that provides support for delivering messages between different parts of your single-page application. This feature is frequently used in Angular because it is responsible for handling multiple values, asynchronous programming in Javascript, and also event handling processes.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In this simple example we'll call an api recieve an Observable and just console.log it out.&lt;/p&gt;

&lt;p&gt;Just before that let us brush up two concepts&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;What is Observable? &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Observable is a function that converts the ordinary stream of data into an observable stream of data. You can think of Observable as a wrapper around the ordinary stream of data.&lt;/p&gt;

&lt;p&gt;Observable stream or simple Observable emits the value from the stream asynchronously. It emits the complete signals when the stream completes or an error signal if the stream errors out.&lt;/p&gt;

&lt;p&gt;Observables are declarative. You define an observable function just like any other variable. The observable starts to emit values only when someone subscribes to it.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;What are observers/subscribers?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The observers are the ones which consumes the value emitted by the observable, these are called observers or subscribers.&lt;/p&gt;

&lt;p&gt;The observer must subscribe with the observable to receive the value from the observable. While subscribing it optionally passes the three callbacks. next(), error() &amp;amp; complete()&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Creating an Observables&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; obs = new Observable((observer) =&amp;gt; {
    console.log("Observable starts")
      observer.next("1")
      observer.next("2")
      observer.next("3")
      observer.next("4")
      observer.next("5")
  })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Subscribing to it&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;this.obs.subscribe({&lt;br&gt;
      next: (v) =&amp;gt; console.log(v),&lt;br&gt;
      error: (e) =&amp;gt; console.error(e),&lt;br&gt;
      complete: () =&amp;gt; console.info('complete') &lt;br&gt;
    })&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;Returning an observable and subscribing it during an API call&lt;br&gt;
 *&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;catAPI() {
    return this.http.get&amp;lt;Observable&amp;lt;any&amp;gt;&amp;gt;('https://catfact.ninja/fact')
  }

  callingCatAPI(){
    return this.catAPI().subscribe( val =&amp;gt; {
      console.warn(val);
    })
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Rest API with Golang and Cassandra DB</title>
      <dc:creator>Parth Shukla</dc:creator>
      <pubDate>Wed, 12 Jan 2022 11:02:36 +0000</pubDate>
      <link>https://dev.to/parthshukla/rest-api-with-golang-and-cassandra-db-10o</link>
      <guid>https://dev.to/parthshukla/rest-api-with-golang-and-cassandra-db-10o</guid>
      <description>&lt;p&gt;Apache Cassandra is a highly scalable, high-performance distributed database designed to handle large amounts of data across many commodity servers, providing high availability with no single point of failure. It is a type of NoSQL database.&lt;/p&gt;

&lt;p&gt;In this post we'll be creating a REST API form Golang and Cassandra DB.&lt;/p&gt;

&lt;p&gt;Firsly I'll outline of this blog.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Create a keyspace of Cassandra (Similar to Database in MySQL)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create a table inside the keyspace &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Connect with go-cql connector &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create the rest-api&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;NOTE: This blog is being written according to an ubuntu system so there may be some minute changes according to your OS.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Create a keyspace of Cassandra&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE KEYSPACE users
WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 1};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A replication factor of one means that there is only one copy of each row in the Cassandra cluster. A replication factor of two means there are two copies of each row, where each copy is on a different node.&lt;/p&gt;

&lt;p&gt;The details of these terms are not the focus of this blog thus I will explain in it in some later blogs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Create a table inside the keyspace&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use users;

CREATE TABLE stu(
   username text PRIMARY KEY,
   email text
   );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;TIME FOR SOME GOLANG !!!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Firstly we'll create a main.go file and inside it we'll create a struct to map with the database structure&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type Student struct {
    Username string `json:"username"`
    Email    string `json:"email"`
}

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

&lt;/div&gt;



&lt;p&gt;For connecting with the cassandra we'll use gocql package and link of it is given below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.tourl"&gt;github.com/gocql/gocql&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we will create our main function and start the server&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    http.HandleFunc("/", handleRequest)
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
    fmt.Println("Server has Started")

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

&lt;/div&gt;



&lt;p&gt;For our cassandra client we'll create a new struct named Client which will have a pointer to gocql.Session which has all the required functionalities to interact with the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type Client struct {
    cassandra *gocql.Session
}

var cassandraClient *Client

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;The IniitalizeDB() function&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This function is responsible for creating a connection between cassandra and Go and returning a *Client type variable&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func InitializeDB() *Client {
    cluster := gocql.NewCluster("127.0.0.1")
    cluster.Consistency = gocql.Quorum
    cluster.Keyspace = "users"
    session, _ := cluster.CreateSession()
    fmt.Println("********************** Cassandra Initialized")
    return &amp;amp;Client{cassandra: session}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we call the InitializeDb() in the main function and pass the cassandraClient in a variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cassandraClient = InitializeDB();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we map the request to functions according to the POST, GET, PUT, DELETE&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func handleRequest(w http.ResponseWriter, r *http.Request) {
    switch true {
    case r.Method == "POST":
        createStudent(w, r)
    case r.Method == "GET":
        getStudent(w, r)
    case r.Method == "PUT":
        updateStudent(w, r)
    case r.Method == "DELETE":
        deleteStudent(w, r)
    }

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

&lt;/div&gt;



&lt;p&gt;Atlast all the setup is done now we create the CRUD operations:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. CreateStudent function&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We have 2 functions firstly createStudent function which takes in the post request and routes it CreateStudent function which does the database query.&lt;/p&gt;

&lt;p&gt;to Insert into cassandra we use the query.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;INSERT INTO users (username, email) VALUES(?,?)&lt;/strong&gt; and then add in the values.&lt;/p&gt;

&lt;p&gt;the functions are below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func createStudent(w http.ResponseWriter, r *http.Request) {
    var NewUser Student
    reqBody, err := ioutil.ReadAll(r.Body)
    if err != nil {
        fmt.Fprintf(w, "wrong data")
    }
    json.Unmarshal(reqBody, &amp;amp;NewUser)
    //Call the DB
    err = cassandraClient.CreateStudent(NewUser)
    if err != nil {
        panic(err)
    }
    fmt.Println(NewUser)

}



func (s *Client) CreateStudent(stu Student) error {
    err := s.cassandra.Query("INSERT INTO users (username, email) VALUES(?,?)", stu.Username, stu.Email).Exec()
    if err != nil {
        return err
    }

    return nil
}

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

&lt;/div&gt;



&lt;p&gt;Similarly for the other methods&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Update Student&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;UPDATE users SET email=? WHERE username=?&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
func updateStudent(w http.ResponseWriter, r *http.Request) {
    var UpdateStu Student
    reqBody, err := ioutil.ReadAll(r.Body)
    if err != nil {
        fmt.Fprintf(w, "Kindly enter data properly")
    }
    json.Unmarshal(reqBody, &amp;amp;UpdateStu)
    //DB Call
    err = cassandraClient.UpdateStudent(UpdateStu)
    if err != nil {
        panic(err)
    }
    fmt.Println(UpdateStu)

}



func (s *Client) UpdateStudent(stu Student) error {
    err := s.cassandra.Query("UPDATE users SET email=? WHERE username=?", stu.Email, stu.Username).Exec()
    if err != nil {
        return err
    }
    return nil
}


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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Get Student&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SELECT * FROM users WHERE username=?&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func getStudent(w http.ResponseWriter, r *http.Request) {
    name := r.URL.Query().Get("username")
    //DB call
    stu, err := cassandraClient.GetStudent(name)
    if err != nil {
        panic(err)
    }
    fmt.Println(stu)
}

func (s *Client) GetStudent(username string) (Student, error) {

    stu := Student{}
    ctx := context.Background()
    err := s.cassandra.Query("SELECT * FROM users WHERE username=?", username).WithContext(ctx).Consistency(gocql.One).Scan(&amp;amp;stu.Username, &amp;amp;stu.Email)
    if err != nil {
        return stu, err
    }
    return stu, nil
}


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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Delete Student&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func deleteStudent(w http.ResponseWriter, r *http.Request) {
    name := r.URL.Query().Get("username")
    //Db Call
    err := cassandraClient.DeleteStudent(name)
    if err != nil {
        panic(err)
    }
    fmt.Println("Successfully Deleted")

}


func (s *Client) DeleteStudent(name string) error {
    err := s.cassandra.Query("DELETE FROM users WHERE username=?", name).Exec()
    if err != nil {
        return err
    }
    return nil
}


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

&lt;/div&gt;



&lt;p&gt;So now if you want to access the whole code here is the link &lt;br&gt;
&lt;a href="https://github.com/mrshukla1805/golang-cassandra"&gt;https://github.com/mrshukla1805/golang-cassandra&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Please do provide a star on the repository!!&lt;/p&gt;

&lt;p&gt;Enjoy and keep learning ;)&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
