Learn Go Programming by Building 11 Projects – Full Course

**Building a Wolfram API Bot with Golang**

In this tutorial, we will build a simple bot that uses the Wolfram API to answer questions. The bot will be built using Golang, a popular programming language for building scalable and efficient software systems.

**Creating the Wolfram Client**

To start, we need to create a Wolfram client variable in our Go program. This variable will hold the API key from Wolfram, which is required to make requests to the API. We will also create a `wolf` constant that holds the base URL of the Wolfram API.

```go

var wolf = "https://api.wolframalpha.com/v2/result"

const wolframAppId = os.Getenv("WOLFRAM_APP_ID")

var voltronClient string = fmt.Sprintf("%s@app_id=%s", wolf, wolframAppId)

```

In the above code, we create a `wolf` constant that holds the base URL of the Wolfram API, and a `wolframAppId` constant that holds our API key. We then use these constants to create a `voltronClient` variable that will be used to make requests to the Wolfram API.

**Defining the World Front Grant**

To authenticate our requests to the Wolfram API, we need to define a world front grant. This is done by creating a string that starts with `/ wolfram alpha/` and includes our API key. In this case, we will use the following string:

```go

var grant = "/wolf@ramalpha/"

```

**Creating the Bot Program**

Now that we have created our Wolfram client and defined our world front grant, we can start building our bot program.

First, we need to import the necessary packages, including `encoding/json` for handling JSON data, and `fmt` for printing output.

```go

import (

"encoding/json"

"fmt"

"io/ioutil"

"net/http"

)

```

Next, we define a function called `getAnswer` that takes in a question string as input. This function will be used to make requests to the Wolfram API and retrieve answers.

```go

func getAnswer(q string) (string, error) {

url := voltronClient + "?query=" + q + "&format=json"

resp, err := http.Get(url)

if err != nil {

return "", err

}

defer resp.Body.Close()

var rds struct {

Result struct {

Explanation string `json:"Explanation"`

Code int `json:"Code"`

Status int `json:"Status"`

Data struct {

Explanation string `json:"Explanation"`

Code int `json:"Code"`

Status int `json:"Status"`

Value string `json:"Value"`

}

}

}

err = json.NewDecoder(resp.Body).Decode(&rds)

if err != nil {

return "", err

}

value := rds.Result.Data.Value

return value, nil

}

```

In the above code, we define a function called `getAnswer` that takes in a question string as input. We use this function to make requests to the Wolfram API and retrieve answers.

**Running the Bot**

To run the bot, we simply need to call the `getAnswer` function with a question string as input.

```go

func main() {

q := "query for bot who is president of india"

resp, err := getAnswer(q)

if err != nil {

fmt.Println(err)

return

}

fmt.Println(resp)

q = "query for bot what is the capital of china"

resp, err = getAnswer(q)

if err != nil {

fmt.Println(err)

return

}

fmt.Println(resp)

}

```

In the above code, we call the `getAnswer` function with two question strings as input. We print out the answers to these questions.

**Conclusion**

In this tutorial, we built a simple bot that uses the Wolfram API to answer questions. The bot was built using Golang, a popular programming language for building scalable and efficient software systems. We created a Wolfram client variable, defined a world front grant, and built a bot program that makes requests to the Wolfram API and retrieves answers.

"WEBVTTKind: captionsLanguage: enif you want to take your go programming skills to the next level this is the course for you experienced go developer akil sharma will teach you how to build 10 projects using go the projects go in order of difficulty starting with a simple web server so in this video we learn how to build a very basic golang web server the prerequisite to this video is that you should have golang installed on your system and you should have a very basic idea of how golang works like packages trucks and interfaces and uh you can watch a video on how to install golang if you don't have it on your system and it doesn't matter if it's open to mac or windows the steps that i'll be covering in this video will be similar for all of them so i i'm on my windows laptop and i've opened my up my powershell uh which is basically a terminal for windows and on mac you'll have terminal on opendo you'll have uh your bash or your terminal again so you once you've installed golang on your system you'll have a folder called go so that's where you want to be you want to be inside that folder called go and inside this folder you want to be inside a directory called as src inside this src directory uh we'll create a new directory called go server and we'll go inside this directory this is where we create our code so i'll open this in my code editor which is vs code so now that i'm in my code editor i'm going to go ahead and create a folder called static where i'll keep my html or static files and my main dot go file where all my golan code will reside as you know when we start writing any golan code we have to write package main in the beginning and then we have to import some packages from package main so one uh of the packages that i need is fmt then i need the log package then i need net slash http package which has most of the functions that i need to create a web server and routes right and then as you know for every golang code we have to have trunk main which is where most of the control of the operation lies right now i'll switch over to my draw.i o board and show you what exactly we're building so i thought before we start building any of the functions it's better to show you uh what we're building so we here's our server file and here are the three routes that we'll be building today one is the root route which is just a slash then we have slash hello and then we have slash form when we hit the slash route or the root route we'll just open up index.html file and then we have slash hello uh which will just uh call function hello function and just print hello to the screen and then we have a slash form route which will have a form function associated with it and then that will open up a form.html file for us right so we have to create index.html and form the html files right now and then we have to write these routes inside our funk main and then we have to create these functions also inside our main.go file right so now that you have a 10 000 feet view of what we're doing it'll just uh everything will make a lot more sense so now let's uh switch back to our vs code back in our vs code you have seen that we had worked till this point till funk main now it's time to create two files index.html form dot html in our static folder in index.html we'll write some very basic code we'll say html and then we'll say head and sorry we'll say title here we'll say static website and after the head we'll place a body tag inside the body tag we will have an h2 tag and we will again say static website and that's that's about it in our form we'll have slash doc type html then we have an html tag we'll have a head tag inside the head tag we'll say meta card set is equal to utf-8 slash right so that's what our meta tag does and then we have our body tag which will have a div it will have a form method is equal to post right so we want to post the form and then we will have slash form right and then we have our label uh i'm i'm assuming that you already know uh html so i'm not explaining a lot of things right but anyways this is the name field that we want the user to input right so we'll have input name is equal to name and then you have type is equal to text and you can also skip this part if you don't really uh you know want to bother about html and then you have label then you have address then you have your input name is equal to address and type equal to text and value nothing right and then you have your end code type is equal to your submit button value submit so a submit button which will have submit written over it all right and this completes our form that we want the user to fill right and now we want to start wiring up our main logic which is inside the funk main so inside funk main we'll have a file server which is basically uh a function that we get inside the hdb package that we just imported so let's say file server where s is capital so make sure you say that and here uh you have a short form assignment operator which basically declares and defines a variable right so with colon and is equal to and then you have http dot directory dot static slash static i meant so we're telling uh golang that we want you to check out the static directory and now golang automatically knows that it has to look at the index.html file because uh as you know php golang node.js all of them look at the index.html file right that's what they're trained to do as servers and now you have a handle function inside your hdb package right and so i want to start handling my root route which is just the slashed out so how do i handle it i say send that to the file server function that i just created which is you know just on top of this and then you have your http dot andrew funk which handle funk is another uh what he called function that we get inside the http package and now i want to handle my slash form route and you have form handler right so we'll create the form handler function shortly and then you have another handle func where we'll handle our slash hello function right slash hello route that which we'll call the hello handler function so far so good i've already shown you what slash hello and slash form are supposed to slash form will show us the form which is from.html just the slash will serve as the index.html file which i've shown you how it will do that and slash hello will just print out hello to the screen and we'll have to create a function called hello handler for that and now let's also print out what will be printed out when our server connects so server.port 8080 and right so if you want to put new line you have to use printf which is inside the fmt package that we've just imported now let's handle our server so we uh you know use the listen and serve function inside the http package so as you can see hd packet is very important and this will create the server so this is really the heart of the software that you're creating right so they can be uh the error can be there or it could be nil so one of these two values will be assigned to err which is the error so now let's handle the error if it's not equal to nil then we want to do something so we want to log dot fatal error and this is where we used our log package to handle or to you know log the error so so far so good with the main.go now we want to start creating our main functions so first we'll create the hello handler and func hello handler this usually has two things so one is w and the other is r right so w is http dot response writer so as you know with any api or any route you'll have either a response and a request so request is something that the user sends to the server and response is what the server sends back to the user so we'll keep that value in w which is the response and for the request that the user will send which will be in http dot request this star is a pointer so r is basically pointing to the request right so yeah i'm assuming you have basic idea of how pointers work even if you don't uh it's okay i think you can just follow this video right so as soon as we wrote funk uh hello handler you can see the squiggly line below hello hundred went away because now it's uh it knows what to do when it uh you know encounters this route now let's start writing out our function so url r is as you know the request so when the uh user sends a request which will be in the form of like let's say slash hello right so what you want to see is if user dot if the r url dot path is not equal to hello now we're sending the uh the request which is slash hello to the hello handler but let's say by mistake something comes here so now we want to check if uh you know the path is not yellow handler then we'll do something we'll say sleepy dot error w slash 44 not found and http dot status not found all right and we'll just return from the function and then if r dot method not is equal to get so we want only uh like when you type slash hello in your browser right that default by default is a get method right and we don't want people to post anything to slash hello we want people only to get and in the sense just print out hello right that's why we're saying that if it's uh not get then again you'll return an error http dot error which will be w again and method is not supported then you have http dot status not found now again status not found is again inside http packet so you can see how important that is and then we'll again return from this function if this is the condition but the ideal condition would be that we want to just print to the screen which is f print f so fmt by the way has a lot of these uh you know functions like printf print ln fprintf right you can check them out and they're all for very different things and so we'll say hello and that's what our hello handle will do now there's this quickly line below form handler so that means we want to write a form handler function so let's start doing that so we'll say funk form handler w http dot response writer and our asterix http dot request now uh you're going to be using this very often so just i mean it's the same syntax so uh you can keep it copy paste it somewhere and then just keep copy pasting it that's completely all right and again we'll have the same thing if error parse form so you want to parse a form right uh we want people to submit something in their form their html file and there will be a post request and they will then that will parse the form error not equal to nil basically if there is error then we want to say print fmp dot f print f w error okay didn't we look done so this is just basically printing out the error and here we'll say f print if w comma post request successful which is the ideal scenario which is where you want to be and we'll say name is equal to so whatever we'll fill in the form right you remember the form so whatever we'll fill in the form uh we want the values to be taken into these variables so r dot form value name so we want name from the form to come to uh name and then we want address to be equal to r dot form value address and we'll say fmt dot f printf w comma name is equal to percentage s new line comma name and then we say fmp dot f f printf is basically printing it on the screen print f comma so whatever the the user has written so we're just going to basically um printed out here now uh you must have seen that there was a squiggly line below and a name and then once we used name out here the squiggly line went away because golang tries to tell you that you're you've defined this variable but you're not using it so that's an error in golang and this doesn't happen with javascript and you can have like millions of variables that you never end up using and that's a problem right uh so that's a nice thing about golang that it catches all of that and then you'll say address so now the squiggly line below address is also gone away now this completes our function so let's uh head over to the um powershell and check it out if it works so back inside our terminal or powershell we're still inside that folder go dash server where we've written all our code and now we're going to run a command called go build which will create a binary executable file it'll be a dot exe file because i'm in windows and um now i can run go run main dot go so we have given our main file the name main.go but you could have named it anything else but main.go is the usual accepted standard right so that's why we named it main.go now we're going to run that code and it's going to say starting server at port 8080 because that's what we had written if you remember in our funk main uh it's it's given me so it's showing me a pop-up which is asking me for my permission for my firewall so i'm going to allow access you might not see that in your in the screen recording software probably now we'll have to head over to our browser to see what's happening out there so let's go to our browser and here we'll open a new tab we'll say localhost 8080 now you remember we have three uh routes we're handling three different routes right so one is the route route which is this just the slash then we have slash hello and then we have slash form.html right so we have those three uh routes that we're handling so slash we're handling uh using file server and then we're handling hello using hello uh hello funk handler uh the function hello handler function then we're handling slash form using the uh form handler function right so in the diagram if you see this right slash hello slash form and then with slash we want to open up the index.html file we just written static server and that will be printed to the screen and then we have slash hello where we just want to print out hello to the screen and then we have a slash form where we open up a form from the html file and then we'll have we'll fill up the form and then we'll you know post to the server and print out something to the screen again all right so let's uh start off by checking out the slash route and see what happens it says static website right which is exactly what is written inside the index.html file and if we say slash hello uh the hello handler function will be called and you will just print out hello uh to the screen and then if we have form dot html i'll just enter my details here and submit so remember it'll say posts request successful because that's what we had written in our code right inside the form hillary function and after uh you know you submitted those details it's just going to print out those details to the screen that's all it does so f printf name and f printf address if you remember writing that right so it's just printing out those values to the screen that's what our simple web server in golang does in this video we'll build a complete crud api using golang and we'll have something called as a movie server which will give us the list of all movies and we can create update and delete as well that's what crutch stands for and uh this diagram is a 10 000 feet view of what we'll be building so that once we start coding you won't have any um confusions right of what why we're doing certain things so there won't be a database that's why i put a big cross here that we are not going to use the database we'll instead use trucks and slices to actually perform operations on the data inside the server itself and uh we'll be um serving it on localhost 8000. we'll be using gorilla mux and gorilla mux is an external library so i'll show you how to install it as well and so we'll have five different routes so we'll have get all route we'll have a get by id route create route update route and delete route and that's something you need to remember because uh once we start coding you'll understand why i have shown you this diagram so every single route will have a corresponding function so if it's a get all route it'll have a get movies function if it's get by id then you'll have a get movie function uh without the s and then if it's a create route we'll have a create movie function and so on for updating delete as well right now there are two types of endpoints slash movies or slash movies by id and we have to use them depending on what we're doing in the sense if we're creating then obviously it's slashed movies if you're updating then obviously the id is required so it has to be slash movie slash id right then there are methods so there are get methods for get all and get by id we'll use get method for create we'll use post for update we'll use put and for delete we'll use the delete method and we'll be using postman to test all these endpoints using all these methods right so um what we'll start doing now is we'll start first we'll create a directory for uh keeping this project and then we'll start writing the code and then i'll take you to postspan to test all the apis so the prerequisite here is that you need to have golang installed on your system uh now i'll see you on the powershell so now we are at our powershell for windows we have powershell for ubuntu or mac you'll have your terminal uh is the same thing and the commands that i'll be writing here will be exactly the same for uh mac and ubuntu as well so you don't have to worry uh now the prerequisite like i said is that you should have golang installed in your server on your system i meant and that means that you'll have a folder called as go in your system right so you have to go inside the go folder you have to go inside src if you don't have src then you can create src but you'll definitely have been in uh package i think so you can create the src folder and now you're inside the src folder right as you can see here uh now we'll create a directory called go movies product and we're going to see it inside this directory right and like i mentioned in the beginning of the video that we'll be using gorilla marks now gorilla mux is not part of the main package that you get with golang right so it's an external package so uh the way to install that is using goget and you have to put the github.com uh link for the same right so the link for gorilla is gorilla slash mux and then github.com then you use go get to get it and then once i hit enter it's going to install it or in my go moviestrad folder now i'll open up my code editor window you could use notepad plus plus i'm using vs4 in this video so i'm going to open up this folder in code plus in vs code like i said and i'm going to try and shift to the visual studio code so i think now you can see vs code on your screen as well and here we'll create a file called main.go now this video is a beginner friendly video so i'm not going to have different folders and a very complex project structure which will have routes and controllers and models and database and all of those files and folders because that will uh you know i'll have to configure the go path i'll have to configure the relative routing and all of those things so i don't want you to be confused if you're a beginner so if you've just learned golang and you just want to get your hands dirty with building a server and building a rest api this is the right video for you so i'm going to try and write everything in the main.go uh file right so so that you don't get confused and this is also why i'm also not using a database and i'm using just structs and slices to actually manipulate the data inside golang itself and so let's get started so as you know that when we write the main.go file the first thing that we have to write is the package main right so and then we start importing the packages that we need so i know that i'll be using fmt because i'm going to be printing out stuff like your server is connected and that kind of stuff i know that i'll be using log because i want to log out the errors if there's any error for connecting to the server and then i'll be using encoding json or by the way all these are part of the package main so you don't have to really uh you know worry so encoding slash json uh i need this because i want to encode uh my data into json when i send it to postman and then i need math slash random we'll be creating uh so let's say the user adds a new movie to this movie server so we need to create a new id for it and that will be created using math.math random so that's why i need that and then i obviously need net slash http because this allows us to create a server in golang so that's it's quite important obviously and then you have your string conversion uh because the id that i'll create using math.random will be an integer and then i'll have to convert into a string so i'll use string and string convert and i'll use itoa to format the the integer and then um you know convert into string so and then i'll have the external library that we just installed which is gorilla marks so you'll say github.com and slash word class remarks now you'll get a quick line for all these packages because uh you have imported them but you're not using them so golang knows that and golang is going to trouble you till the time you start using those packages and which will be quite soon for us so we'll start using them soon now uh if you remember i told you that we won't be using a database we'll be using structs and slices right struct is basically like an object in um in javascript if you view javascript or java or any other language it's like an object and you're going to define you are going to have almost like key value pairs and you're going to define uh you know the types of data inside that so i'm going to have a struct of type movie and i'm going to have uh start of type director okay and movies and directors are going to be associated in the sense that every movie has a director that's how they're going to be associated so movie will have multiple other things he'll have an id which will be string right and then you put this character which is i think called carrot not sure this is directly below the escape button on your left on your keyboard and then you say json and then you say id within double quotes then you have isbn which is basically just a number uh assigned a unique id assigned to a film and then you have again those characters and then you have json and isbn it's right struct here then this quickly like hopefully go away and then you would have the title of the movie obviously the movie has a title right and you'll put string here and then you put a json and then you'll say it's title then you have to say director star director and json and star is a pointer as you know uh so that means if i create a struct call director it will be associated to movie struct and with director what i'm saying is that director will have the same values that i'll define inside the director right so these are strings idea has been entitled strings but director is a type of director which is the struct that i've defined which i'm defining right now and director will have first name which will be a string json and hostname and we'll have a last name so again djson right so when we send this data using postman we'll be using isbn id title and director in small with small you know what do you call it small caps same with first name and last name that's why we're defining json like this so that we're able to encode and decode the json when it comes from postman and so we've defined our two structs and like i said movies are associated to directors right every movie has one director and then we'll have our so we'll define a variable called movies it will be a slice of the type movie this right so because we'll be using movies very often now you'll see why uh i won't try to explain it i'll just show you uh instead so we as you know every golan code every go file has funk main right in funk main you will have your uh so in golang i'm sure you know that you have colon is equal to which declares and defines the variable at the same time so you'll have much dot new router new router is a function inside the mux library inside correla so r is now your new router router and then you'll have r dot handle funk and you'll have uh five functions here so let me take you back to the yeah chrome and show you those five functions so we'll have uh five routes as you remember one two three four five and we'll have five different functions right so inside our uh funk main file itself funk main function itself we'll have to define these routes and functions so let's go back to the code window i'm not sure if you can see it yeah so now you can see it so i'm back at the code window and now i need to create five different routes and five different functions right so first route is the movies route i'll get movies get movies will be the function so if i hit the get move slash movies route i'll need to take it to the get movies function which i'll define in some time till the time i don't define it it's going to give me a squiggly and say that you don't have this function and the method i'll be using here is get you've seen this on the diagram that i'll be using get method for getting all the movies right then you'll have our dot handle fun slash movies slash id and get movie so as you can see there's no s here it's get movie get a singular movie and methods again is get then you have another handle funk slash movies and methods is post then you have r dot handle i'm not copying and pasting r dot handle from this line uh i'm typing it again and again because i want you to type as well and that will ensure that you have some muscle memory and then you'll be able to write code on the fly really quickly and you won't make a lot of mistakes so it's always good to write it again from scratch so you have a function here called update movie then you have methods and say put and say r dot handle funk slash movie slash id again we have delete movie dot methods delete okay so we have the functions we have the methods and we have the routes so all of that makes sense and to start the server what we'll say is so first we'll have to print starting server at port 8000 slash n right and i'm going to say i'm going to log out if the server doesn't start and i'm going to put i'm going to use the listen and serve function inside the hd package that i have here http package so to start a server it's very simple in golang right all you have to do is http dot listen and serve that that's all you have to do you have to write the name of the port so i have to put this code in front of it because localhost colon8000 right uh we'll be hitting that address when you start the server so i have these five functions get movies get movie so i have to create all those five functions and i have the method set out here now before i do any of that when we go to our postman and we'll hit the server right when we hit the api uh slash movies and we want to get all the movies in the beginning there won't be any movies so that uh we don't want that we want it to have at least a couple of movies right so that we know that the server the api is working perfectly otherwise we'll never come to know so what i'm going to do is i'm going to take movies struct uh this slice of movies right that i just created here that's what that's what i was saying that i'm going to show it to you very soon so you don't have to worry about it so we have the slice called movies and i'm going to append a couple of movies to it and by the way all the operations that we'll be doing in this and all these five functions will be around uh this slice called movies because we'll be storing a lot of these different movies uh and the type obviously is this this is an entire type right or you can call it a class or an object or whatever this is an entire type and then we'll have multiple movies of this type the complete structure right and then you have uh movies append and then you have movies right because we want to append to movies and you want to append a movie to movies right which will be an object just like this it will be an object a struct and we'll have to define all these things like id isbn titled and all those things so i'll say id 1 also isbn 4 3 8 2 7. let's say title movie one and for director the syntax is slightly different okay so you'll say director and then you'll say ampersand director because we want the reference object we want the reference of the address of director right which is this out here that's how we'll be able to use the pointer director so if you've used pointers in c or any other language you'll just know that ampersand is to give you the address and percentage or so the aztecs is used to access that address for the pointer and then you have uh the directory which is first name john and last name so i have one movie i will create another movie append movies movie object and it will have an id oh just a second essentially some issue yeah so it will be id 2 ispn 4 5 4 then you have your director again first name so what should be a good first event last name let's keep it steven smith and last name because smith i'll actually keep the s capital even with yeah steve s capital i think so like i said we have our movies so when we now hit the get movies function at least we'll have two movies that will show up right so we'll at least know if the api is working and the server is working fine and now let's start creating our get our movies function what i'll do is i'll create the get all movies function then i'll create the delete function and then i'll create the get movie function create function and update function the update function is uh it will look a little complicated to you it will be the most intimidating so i want to calculate it last so that you at least get used to the syntax before that so let's create get movies okay w http dot response writer comma r star http dot request so we point uh passing a pointer of the request that you will send from your postman to this function and w is the response writer so when we send a response from this function it will be w right so we'll say w dot header dot set basically we want to set the content type as json right so we want to work with json the thing is that um the struct uh our golang stack needs to be able to convert the json coming uh into it into uh you know its own format so that's why we have to set this content type and then we'll say application slash json and then we'll say json.new encoder which we got from here encoding json right json this is the same json json.new encoder and you're going to encode w basically the response that you want to send to it you want to encode it into json and dot and code and you want to pass the complete movies slice that you have so like i said you know whenever we uh when we're whenever we create slices we're just going to append um you know a new movie to the movie slice that already exists whenever we want to update anything we'll be uh traversing inside movies and we'll be updating something inside the movies slice as well so movie slice is quite central and when we all obviously when we return uh the list of all movies we'll be returning or resolving basically the entire movie slices at the same time so this is why the movies uh slices at the center of uh this entire operation that we're doing right now uh so you've seen how now you know how you can get all movies right so you basically uh want to you know encode into json and then you want to just encode movies and send the json of all the movies of uh the slice which has the type struct which is struck movie right so all of these movies you will be able to send to the front end or to postman or wherever now we'll create the delete function because that also looks a little easy right and then we'll get into crea get one and create and delete functions so let's delete them now when you want to delete a movie you'll be passing an id of the movie so we'll say w http dot response writer again and r star http dot request you'll have w dot header dot set again the same thing content type and you want it to be application slash json and now i'll get some params right so the id that i'll pass from my postman which will will go as a param to uh this function create movie and that param uh which will be the id will be present inside mux dot vars and inside the response sorry the request which is r so it will be part of the request right the pointer to the request i'm sending out here so in params now i have the now i'll be able to access the id so what i'll do is i'll range over movies ranging over movies if you used javascript it's very similar to like for each basically so all you're doing is you're just going over all of the movies and you want a put you want to find a particular movie and uh now what you want to do is if item dot id or the id that you pass so you'll say that delete uh the id uh two in the sense the movie with the id2 right so the id which you now have uh right access to which will be params id so you know that we got params we got the id that you sent as a request to this function will be inside params and will be inside id so you'll have access to that particular movie uh that particular id i mean and um and inside movies you will go uh through all the movies one by one and each of the movie will be inside items so item that with item.id you'll be able to access each of the ids of the movies of each of the movies right so if uh the item dot id of a movie which is inside our uh movie slice is equal to the id that you just passed as a pronounce to the request then what should we do we should take the movie slice and we should append basically we want to delete it right so we appending it i'll show you how you can delete something by using append so we'll say movies and index so for range for a range function right you have to pass index an item index is like you know i is equal to one well this very much like javascript like so so for index you have i so i uh you know starts from zero and goes to a particular value and item is actually the item so if you used a for in loop or a for off loop you would know that you can access or iterate over the exact items itself and in go like you can do both at the same time and you'll have movies index plus one and dot so what you're doing here essentially is whatever id that's matching right now that you want to delete it's going to basically take that and directly append all of the other uh you know data which is basically index plus one all of the other data is going to just append it in that place in this place so that means this movie now won't exist it's the id that you just passed with the index it won't exist because in in place of that the entire movie's uh you know uh index plus one after that all the movies that were there they came out here right in this place so the movies uh movies that you want to delete now will not exist so that's how you delete a movie right using a pen now we'll get a particular movie by using get movie function so we'll create the get movie function and again we'll have w http dot header dot set and again your content type comma application slash json then just the same way we did with a delete movie uh you will get params the id in the params right in the same place exactly where r where r is the request that the user sends and mux is the package that we're using for creating these routes and vars is inside mugs right which helps us to uh get access to the all the things and uh requests so basically the params and uh then we'll loop through the movies one by one so if i want to get a particular movie from the slice of the movies that i that exist uh with me in golang all i have to do is i have to go through all the movies and then find that one and then encode into json and send it to the front end or to postman right so here we'll again use the for loop just like we did in delete movies uh but there'll be a difference here instead of index we'll write the blank identifier because we don't want to use index because we won't be using index right and if you don't use something in golang you have to use the blank identifier otherwise golang will give you uh those squiggly lines and give you an error that you've defined this variable but you have not used it right that's why we have to use this uh blank identifier now we'll range over the movies and we'll say if item dot id is equal to is equal to parents id right so inside params i have passed an id so it's going to try and compare that with item.id because it's going to range over all the movies one by one and each movie will be inside item and so we'll have the access of id inside the item and that will compare with params or id that just passed and if they're equal then you just have to return it that's all you need to do you don't have to do any other operations so you say new encoder w dot and code item and then you'll just return now uh i'm sure now you can see why i showed you the delete function uh before the get movie function right and that's because in delete function we we used the range uh but we didn't have a blank identifier if if i would have used a blank identifier directly then you would have gotten confused so that's why i want to show you the delete function before now in delete movie once we delete the movie i think it's better to uh also return all the existing movies after you've deleted that movie so what i'll do is i'll uh try and return the remaining movies as well so i'll say new encoder w dot encode movies just like i did in get movies right json.new encoder w dot encode movies right and then get moving we're just sending one particular movie which will be the item as you know that with range you can access each movie using the item right so we're just sending back one movie whereas with delete movies we're sending back all the remaining movies with get movies we are sending back all the movies so get delete get movie i'm sure these are clear now now we'll take a look at create movie so we'll create create movie which obviously is the most important function because you want to create movies it's going to be a post method response writer and r star http dot request the spelling of response is wrong so it's giving me a squiggly line response it's best to keep uh looking at this quickly line so that you can handle all the errors during while writing the code itself so now you can see that i none of the functions have a squig line anymore except update movie because you've not defined it yet so that's why there's a squiggly line there and we have used all of the packages as well so those quick lines have gone except math random and string convert that we'll be using in update movie and update movie is obviously the most uh intimidating function so i have not shown it to you yet and uh that's why we look it at the last and now we have create movie error dot set so this is something that we do every single time right content type comma application slash json then we'll define we'll define a variable called movie of type movie and you'll soon see why and we'll create a blank identifier again we'll decode our dot query so uh while creating a movie we'll send something in the body we'll send an entire movie like this an entire movie like this we'll send it in the body in postman so we want to now decode that body right we want to decode uh that json body and we'll say decode and right so we'll get that value here in this and movie right after decoding it i will say movie dot id so this is where we'll use your string convert and your uh math.random because you want to create a new movie all right so to create a new movie we also need to create a new id which will be completely random id so what we'll do is we'll say random dot which is a function inside random math random library package and we'll say one one two three four five six seven eight you can put as many zeros as you want so i want to value between zero between one and this uh maximum value to create a random value right and then i'll have to now format it into string so i'll say string convert dot ito a which is a function inside string convert package and that's how i'll get a new movie id so i'll say movies is equal to append uh like we saw how uh with delete movies you could append right and now with create movie also you want to append uh just like we did when we created a new movie we want to append the new movie that has just come to movies that's all we want to use it's very simple so we'll say append and we'll see movies comma movie because the new movie that has come out come from the body is now inside uh this movie which uh you know uh we decoded from json into now a format that is readable by golang and it will now look like this it'll look like a struct right so that like we said movies comma and the entire movie so that's what we're doing here essentially we're just saying movies and comma movie that we just received from uh the body that the user just sent from their postman and now which has been converted into a formatted by calling right so uh really simple now since we have appended it here now we want to also return this movie that was just created just to tell the user that hey you know i have created this movie so you don't have to worry encode and movie so the movie is now created now comes the most intimidating function which is update movie function i'll start writing it out update movie and here uh we'll be passing an id right so you know how to get the id right you'll get it in params which will be inside mux dot vas and inside r right the params will be there and then we'll have to again range over all the all the movies and then what we'll be doing for updating movies is we'll first delete that movie uh for the id that you'll send and then we'll just simply add the new uh id that uh uh the new movie that we'll be sending from postman so this is not obviously the right way to do things when you work with databases uh but we're just doing it here since we're not using a database we can get away with that we'll just delete the id of the movie that uh the the movie with the id that you send from postman and then we'll uh uh you know just add the new movie that you'll send the new structure in that same place we added there so uh i hope that makes sense or maybe i'll should i just write some pseudo code and so that it becomes really clear to you so first what we'll do is we'll uh set our uh content type which we always do right and then the next step will be that we'll get access to our params then we'll loop over the movies or we'll range over them to introverted movies then what we'll do is we'll uh delete the movie of of uh the id sorry with the id that we have sent suppose we'll delete it and then we'll simply add a new movie which will be so instead of actually updating uh that particular record in a database we're just deleting it and then just adding a new record from the body that you're sending which is nice little hack and something uh that you shouldn't do when you work with actual databases it's just to show you right now so this is the pseudocode one by one let's start writing out code then right so now we want to set json content type how do we do that we do that by w header dot set content type exterior and we will say comma application sorry application slash one and then we want our parents right so to get parents we'll say params dot where's r we've been doing this till now now we're going to loop over uh the movies and we're going to delete the movie and then we'll add a new movie so we'll do all of those three things now at the same time so we'll say for index now we want to use index in this case so we won't use this blank uh identifier because you want to use index we'll say it's equal to range movies and if item dot id params id what should happen so like i said we'll first so we'll delete over the movies uh using range and then we'll find that uh movie in our movies slice then we'll delete that particular movie with the id that you've sent so if you found it with the id that you've sent now we delete it so we'll say movies is equal to fn so we'll write the exact same line that we've written in delete movies to delete it so we'll say in a inside a pen we'll use the exact same syntax so let's say movies and index comma movies index plus one let's say dot dot right so let me see if that's what we've written earlier yeah there were no mistakes earlier so it's the same thing now we'll say where moving of type movie now because we want to append that movie so that's why we're going to uh try and follow the same code that we've written for create movie and we're essentially going to almost we can copy and paste this whole thing but i'm just going to write it again right so so like i said you know we are adding a new movie the movie that we sent at the body so we'll say equal to json dot new decoder so the id that we have passed so this is the only step that's different from create movie right because we want to have it in the same id we want to use the same id so let's say movie is equal to append movies let's say json.new encoder w dot and code movie because you want to return uh the movie to the user to tell him that hey i have done what you wanted me to do i'll remove these comments since now you already know how this is supposed to work now one thing that we've not done inside update movie is w http dot response all we have to do now i think is right return here and then we're good to go i don't think there are any issues or errors here so i can go ahead and compile this code maybe right so let me take you back to the powershell uh how do i yeah so i'm back in the powershell now so i'm inside i'm still inside that folder go movies crud and as you can see i have that main.go file so all i have to do now is go build i've built it and now we have to say go run main dot it's going to now start the server and it's going to ask me for firewall access maybe you don't see it in your screen because it's a pop-up so i'll say allow access so yeah so now it's running on server 8000 uh now let's go head over to our so let me see if i can do that or i'll have to maybe pause the video and then show you post man yeah yeah i can show you postpartum yes i think you could see it now uh i'm using obs so it's difficult to switch between tabs actually in obs screen recorder uh now i have created this folder called rough just for my own use uh you can you can probably create just a new folder and inside this i'm going to create a new folder called go movies inside go movies i'll have a request the request will be get all then i'll have a new request get by id i'll have a new request again it'll be yeah create then update and delete so forget all all you have to do is http slash localhost movies right so you have to write http double slash localhost colon 8000 slash movies that's what you have to write and let's hit the server and voila the server is working we have got our two movies that we created in our posts in our vs code right because we didn't want this to be empty so we had created two movies using append and in our funk main so these are those two movies let's get a movie by id so i'm going to take the same route here i'm going to put slash one because i want just the first movies like i'll get uh just the first movie as you can see right now i want to create a movie to create a movie i'll just say uh i won't give the id obviously because i uh golang will create the idea and so on and i'll go here and say the body and i'll say raw and i'll say json and now right i'll just try and call i'll just copy paste this one little from my get all i'll copy and paste one movie here in the body i'll change the id i'll say seven else this i'll change the number something else let's see movie seven and the name here i'll say okay sure so it has added that movie called seven but it's not sending me that uh movie seven it should have sent me the 27 here so there's something wrong we'll have to oh sorry i'm still on get so remember to switch to post method here right so when you say send it gives you the movie that you just created which is this movie 7 right and id there's no point of sending id because id as we know it's going to create on its own so i was wrong when i did that so even if i create one more it's going to create one more id with the same values so now when i get all i'll see four different values right now let's try and edit one of these so let's update uh first let me just copy this whole thing here and switch this to put and then we'll put the id of one of the movies here let's put this id here and update right and then we'll have to say send something in the body which will be the new movie the new movie can be copied from here and we can change some of the values like we'll put it on and i'll just say s because i can't spell shot maker say something else here isbn and so let's see what happens so yeah the movie has been updated the movie seven had first name akil sharma now it's just has arnold so even if we get all we'll be able to see that the movie seven has uh so there's one movie with atletico there's on one we with arnold s because we had created two right in the beginning now let's try to delete this so i'm going to first copy this thing and put in delete and then i'll put the id i'll go back here i'll get the id from here so now it's returning me the movie that has been deleted which was movie seven on test so now when i get all i i won't see that movie hopefully i'm still seeing that movie actually why is not working oh sorry it's on get i'm i again i made the same mistakes i have to uh use the method delete for it so don't make the same mistakes that i'm making all right so now there are only three movies so it's returned me all all the movies uh that are now left right so there are only three movies left even if i say get all there are only three movies left let's delete one more let's read this one also so that only two movies will be left so yeah only two movies are left now right so remember to change the method when you're using postman we'll be building a bookstore management system using golang so we'll be building some cred apis and these are beginner friendly you'll be using mysql database we'll be using the gogorm package to interact with our database and then we look at json marshalling and marshalling and the biggest change here is that we'll have a proper project structure in the sense we won't be writing all of our code in main dot go file we'll have a proper project structure which i'll explain to you shortly and then we'll be using gorilla mugs so with project structure this is what we're going to do we're going to have two main folders in our project one will be the cmd folder the other will be the package folder the cmd folder would only have the main.go file and the package folder uh will have the config folder controllers folder models folder routes folder and utils folder so we'll have six sorry five uh different folders inside the package folder right inside config we'll have app.go file uh which will help us to connect with our database in the controllers we'll have book controllers which will have the functions that will help us to uh you know process the data that we'll get for as response and also the request that we'll get from the user and the response that we need to send so we'll process all of that in the book controller in the book models in the models folder we'll have book.go file which will help us to create those structs and models that will be used by our database in the routes as you know we'll just write our routes and which i'll get into later on in just two minutes i'll show you what the routes are and in the utils we'll just have uh for uh some code for marshalling and marshalling json from our response and our request right and then these are the routes that we have so we'll have uh slash book slash route uh twice one will be for post and one will be forget and these are our controller functions that i've mentioned here so uh if you post on the slash book route uh sorry i think this needs to change this will actually be get and this will be post all right so if you get on our slash book route you will we'll call the get books controller function if you post use the post method on our slash book route we'll create a book right we'll have to send something in the body and we'll have to uh use our uh json master link and much link to uh you know get the data here to the database and then uh we'll if we do get on slash book slash book id which which we'll pass the book id so we'll get the book by id so we'll have to create function to get a book by id then we'll have our put method for updating the book right and on the same route slash box slash book id and then we'll have our delete uh method on slash book slash id route which will give us the delete book uh the function and controller functions so that's our entire uh you know introduction on what we're going to build and how we're going to build it the next steps include where i'll go to my overdue terminal i'll start these uh different folders i'll create this complete project structure and then we'll open our vs code we'll start creating these folders and these files and then we'll start writing all of that right and before that in our ubuntu we'll also have to install the packages that we'll be using so uh in many of the videos that you'll see on youtube you'll also you might see people first including those packages in their uh files while they're coding and then they'll use go mod id or something like that to install the package that they've used but in our case what we'll do is we'll install those packages beforehand and then we'll include them in our code it's just something that i prefer and i also recommend you also do that so that's that's the introduction and let's get started so as you can see i've opened up my terminal uh since i'm on ubuntu this is a terminal if you are on windows it will be a powershell and if you are on mac it will be a terminal again the commands will be the same it doesn't have to uh the commands won't change so i'm going to go ahead and go inside the folder where i write all my go code where all my go programs reside you can do the same and i'm going to go ahead and create a directory for the new project and it will be called go bookstore in my case and i'm going to go ahead and see the inside uh the go book store and now since we are here we'll have to install a couple of packages right so before we install the packages we'll have to create a go.mod file which will uh crea store all the packages it's almost like the package.json file if you are from a node.js background right so it contains all our packages that we'll be using in this project so we'll first do go mod in it and even if you're not storing uh right now inside a github account i just recommend you use github.com and slash your name or any other name and then slash the name of the project which is bookstore this gives us like a relative route or then or an absolute route based on which we can you know include and import different files into our main.go file so it has created our go.mod file okay and now we'll start uh importing the package that we need so the first package that i need is the gorm package which will help me to interact with my database jinzoo slash form so jinzo is the name of the guy i think just created gorm so we have added gorm and now more specifically i need uh the mysql package inside uh guard because gorm uh is a is an orm right it helps for for golang and it helps you to interact with sqlite and postgres but for this example we need mysql so we're going to go ahead and install that and then uh we need to install uh the gorilla mux package since we need to use that for our routes so i'm going to say go get github.com gorilla slash mux so we've installed gorilla mux as well now as per my knowledge uh these are the three packages that we will require but as we go along uh you know i might find that we need more packages so uh it's not a problem we'll install them uh as we go go ahead so from from what i see what be building right now i think these three should be enough probably uh so let's get started with the actual code now that we have our packages in our go mod file uh go mod file also helps us to uh you know go build which will create the build or the exe file which will uh execute on our uh machine exe if you have windows and dot deb if you have uh basically it's a binary file if you have ubuntu and so we're going to go ahead and open up our vs code editor so i'll say code and space dot and that will open up my code editor so as you can see i'm inside my vs code window and now i'll start creating the folders that we had seen in the diagram and you may have noticed that there's a time delay between when i switch between my google chrome and my vs code and my power shell or my sorry my terminal and that's because i'm using obs to record these videos and it's not very user friendly in terms of helping you switch between the tabs very easily so kindly bear with me so let's start creating the folders quickly uh as i've shown you in the in the diagram we have a cmd folder and we have a pkg folder right these are two main folders inside our pk inside our cmd folder we'll have a main folder and inside the main folder we'll have our main dot go file where all the magic will happen right the main controller the main control of our entire project and inside the package uh folder we have config and we have our controllers then we have so i think by mistake what i've done is i've created controllers inside uh config so i have controllers and then i have models and then i have routes and utils right routes and details so as as you've seen just a second back that i had created controllers inside config by mistake and that's a very common mistake by the way and uh that will happen to you if you're not very careful so please make sure that inside your package folder all of these different folders are at the same level inside the package folder right they're not inside one another yeah that's a very common mistake by the way so let's start creating our files inside uh config we have app.go uh inside our controller i i by the way in the diagram i'd already shown you uh the name of the files as well so we have controller.go to control.go and then inside models we have our book dot go file and inside our routes we'll have bookstore routes dot go okay and inside our utils uh the name of the file will just be utils.com now you know there's so many files right here so we need a strategy on where to begin and where to end the program at so how do we start coding how do we begin this whole uh journey of uh writing so much code right it can be confusing it can be daunting it can be overwhelming uh many times so that's why i have a small strategy for you that will help you understand everything really well what i'll do is i'll start with the routes so i'll create the routes first and uh that will help you visualize the routes where the users will hit you know from their front end or from their postman the user will hit on those routes right so we'll start with the routes and then what we'll do is we'll then write our app.go file which will help us to connect with our mysql database then we'll create our utils file so uh app app.go which is the config file and utilize files are very small files so they won't confuse you too much and the routes file is also very small and then we'll create a main.go file the main.go file all it will do is it will just uh you know tell golang that here in bookstore dot routes is where my all my routes reside so all these files will be really small uh then we'll create our models file which will be slightly bigger and then our book controller will have a lot of code so uh we'll tackle it at the end because after the routes the control will go to each of the functions in book controller file so this is the book controller is what we'll tackle at the end and before that you'll get a little bit of an idea of what we're building so it things won't be very confusing for you that's what i'm uh at least trying to attempting to do so uh as you can see i started coding here i've written package routes and then i've said uh started importing the packages that i'll be needing since this is my routes file uh the one package that i most definitely need is gorilla mux which will help me to create the routes in the first place and the other package that i need is not really a package but i need my controller file here so first just see what this is then i'll try to explain to you what's happening so i'll say akil slash go bookstore slash pkg and slash controllers so this will help me import my controllers folder and uh in turn the file inside the controllers folder as well right now if you're from a node.js background you will be very confused when you look at this right so this is uh this is an absolute path whereas with uh node.js you're used to something like this right so you'll say controllers and that's because routes and controllers are both in the same package called pkg so you would say that okay i just want to import controller so i'll just say like this right but that's not how it works with golang golang has absolute parts and once you get used to golang you'll understand that that's kind of the right even if it looks lengthy but it's kind of the right way to do things right because uh this uh the github.com go bookstore uh till here is the path that we created which was like the absolute part that we created for our project when we were initiating the go mod file if you remember and package.controllers is where you know we'll come inside package and then it comes and controls this is where the controller's file lies and that's what we want to use so it may take you a while to get used to this absolute routing but uh but once you get used to it uh i'm telling you you won't go back so i i am a no just developer i was not just developer i can say for a very long time but once i started using golang i can tell you there is no going right because uh golang is so so much better so you have registered bookstore so i want to create a function called register bookstore routes and this function will have basically all my routes and this the routes will help me to get the control to my controller where which is where i'll have meet the meat of the logic so i'll have router marks dot router right and here is where in this function is where i'll create my handlers so router dot handle func right so if somebody comes to my slash book slash right so i'll say controllers dot create book so i've shown you the create book function right in the diagram i have not written the from function till now but i'll be writing this function in the controllers file and this is why i needed my controller's package on top controllers file on top right because if somebody hits the book uh route i want my controllers.createbook function to handle it and the method uh you know is going to be post here because i'm trying to create a new book so i'm sure that's very clear and then we'll create another handle funk and it will again be slash book slash but this time i want it to say get book you'll get the list of all books for me and the method in this case as you know will be get so on top by mistake i had put two h uh for methods i i removed one of those so just make sure you don't make any uh you know typos or any spelling mistakes then we have another handle trunk where we will handle as you have seen in the diagram before the uh you know the scoring part started we'll have slash book and inside this we'll have our book id right and then you have controllers dot get book book by id all right so that's the function i want to get one book by id and dot methods you know the method would be get in this case all right so i think all clear till now now we want to create the two more routes they will be same slash book and slash book id will be there but there will be our put and delete functions right so i'll say router dot handle func sorry and here also i think the us capital it should be a small queue and then you have slash book slash book id and then we'll say inside my controllers file i'll have a function called update book okay and then the method for this will be put and similarly for our delete route as well book slash book id and we'll have controllers dot delete book dot methods and we'll have the delete method here right so so far all looks great right everything is uh working out pretty fine for now so we have written our routes uh package so if you read this far then you should be proud of yourself i think so now like i promise you we'll write the app.go file which is the inside the config folder right and so we'll come here and we'll uh give it the name config package config sorry it's not capital package config all right and here i want to import just two of my packages and they will both be related to talking to mysql so the first package will be jinzu slash gorm which is my orm and the second package will be the more specific one which is dot github.com slash jinzo slash gorm slash dialects slash mysql so if you go and look at the documentation for uh the corn package you will notice this blank character here and then space and then the uh link right so just make sure you do that as well so once we have imported these two packages uh the mysql package and the gom package now is the time to create a variable called db so the the whole point of this file will be to return uh a variable called db which will help the other files to interact with the db right so we'll say star born dot db and then we'll create a connect function the connect function helps us to open a connection with our database and the database in this case as you know is uh mysql database right so we'll have d comma e r r uh the if there isn't so i'll write some statement here and then if there's an error the error will come inside err if if there's no error and the database connection has open it will come inside d right so i'll be able to access the connection using d so i'll say gorm.open which will help me open up my connection with the database right and here i'll write something so i'll i'll say the name of the database that i want to use mysql because gorm helps me as i had said talk to sql lite and postgres as well but in my case i want to use my sql and here i'll say the name of the user and my password and my the name of my table simple rest and and then we'll write some little lines here which are required by mysql so uh if there is is uh you know an error right which means that if error not equal to null which means that if there is an error so we'll say panic er r and here we'll say db is equal to d right so whatever was in d here that we received we'll transfer that to now db variable and we'll have a get db function which we'll use in other files and it just returns deep so like i said you know the purpose of this file is to return um a db variable that will help us to talk to the database other files can talk to database easily now uh as you can see i have not written some code ahead of this part right so for mysql to connect we have to write some things after my username my password and the name of the table so that needs to be care set is equal to utf 8 just make sure you copy this exactly and you have parse time is equal to true so this is some requirement by mysql right so you have location right so these few lines you have to write and then your app.go file is complete now the next code that we'll be writing will be our utils dot go file so when whenever when we start writing our book controller we will be using uh you know we'll we'll need data that is unmarshalled data so we'll we'll receive some requests from the user right and it will be in json but we need to unmarshal it to be able to use it in our controller so we just need to write a one one very small code here to be able to unmarshal uh the json that we'll receive from the request so it's going to be very simple we're going to call it utils package utils and we'll import a couple of packages one is called encoding slash json right the other is called i o slash i o util and the third is called netslash http right and here is where i'll create my function and the function is called parse body that will help me uh to pass the body uh especially in the create function in the sense when i'm when i'm trying to create a book uh you know the create book function in my controllers i will receive somebody in the request right so i need to parse that body because that body will be in json so i need to be able to unmarshal it so i'm just creating one small function to do that right so i get the request and a pointer to it and i take that in r so i'll be able to use r to access the request that i've received from the user and i'm sure you know what a request is you know request has that body that we're sending of the uh the book right and then you have x and you have uh interface so i'm sure uh you know you know basics of how interfaces work so we'll say body and error is equal to ioutil dot read all all we're doing is just reading the body right and if there is no error so error double equal to nil then we'll say error is equal to json dot then we'll start unmarshaling it basically on marshall there's a single l right and we'll say byte and body comma after body you say comma x so just one thing guys the x is a small x not a capital x by mistake i written here capital x just make sure of that and then error not equal to nil and then we'll just return right so even uh this looks like it's complete right and so your utils file is complete and your bookstore routes file is complete now we want to start concentrating on our app.go file yeah sorry the adword file is also complete so now we want to start concentrating on our models file right which is slightly uh more advanced so but let's start anyways right so we have package models we'll call it and then we're going to import as you know we'll import our gorm package first github dot com slash jinzu slash form and there's one more thing that we need to install or import and that will be my config file that i just created right because the config file helps me to connect with my database so i need that here so i'll say github.com right so let me just be sure that yeah this the routes required controllers and the app.go file required gorm and the models required config yeah so i think yeah so we're on the right track so we'll create a database uh the variable called db gordon.db you've seen this already in the config file and we'll create a struct called book structs basically are based on models and a model is something that you know gives us a structure to help us store something in the database so in this case we'll have name because every single book will have a name right and then you put these back two backticks inside that you say gorm then you say json name let me say author and you say string again so name of type string and author of type string and then you say gorm sorry you'll say json and you'll say here author okay and then you'll say publication and string backticks again json again and publication so let me read through it and make sure everything is fine gorm json alright author and publication right name author and publication so we have three things and uh so usually almost like almost always you will find this that we have to whenever we working with databases we have to edit our database so if you've seen the golang to-do list video that i've created so a few days back you must have noticed that init function so here also we need to have an inner function that will help us to initialize the database in the first place so config.connect this is the function that we created together just some time back where which is the connect function which helps us to connect with the database that's inside the config folder you know that already and db is equal to so whatever we get from that um uh you know config file uh by calling the getdb function which we have created together just some time back get db function inside app.go as you can see this is your getdb function which returns just the db which uh you know we had connected to the ddtv right and so that's what you get here inside db so here also you have a db variable where you're just storing the dv that you get back from the config file right so till now i think everything should be highly clear and then we'll just auto migrate it with a book an empty work okay so all good till now uh now you know the control first is in the routes right here in the routes and then the routes basically give the control to the controllers and the controllers will give the control to the book.go which is basically the models right so that's how the flow works in the sense the user interacts with the routes and the routes send control to the controllers where we have all our logic which will write in some time and the controllers then have to perform some operations uh with the database now the the operations of the database have to reside inside our models file which is book.go in this case so that means we'll have to have a different function for the different controllers that we create so we need to have a create a create book uh function here we need to have a get all books get by get booked by id and delete book so we need to have all these different uh functions here right so uh now we have two options one is that i start creating those functions directly or i create the main.go file and then that will give you more clarity and then we create the functions that are required for database right so i think i'll create the main.go file so that you have a little more clarity so let's create the let's go on main.main.go file and then we'll come back to the uh book.go file as well now the so yeah so we have one more option one is that i start creating the controllers and then once we are writing the function the controllers then i'll start creating the model functions but that may confuse you so that's why i want to create the model level functions first which talk to the database right and then we'll have a corresponding function to that in the controls so that i think i feel at least from my opinion that that will make things very easy for you so anyways that let's write out our uh package main file inside our package main file we'll import log because i want to log out if there's any error we'll have nest slash http so as i told you earlier that in our main file all we're going to do is we're going to create the server right which will be which will will also define our local host that's the first thing that we'll do the second thing that we'll do is we'll tell golang where our uh routers reside so basically all that main.go file will do is tell that you know bookstore.routes has our routes so please look there because i don't want to write all my routes in the main.com file right so that means i need my gorilla mux package here slash marks sorry there's slash here and then i need my uh mysql package here github.com dialects slash mysql and then there's something else i need here i need to import the routes right so i know that the routes is inside uh package folder inside that is routes folder so i need to again use my absolute path which will be github dot com slash hill slash go bookstore slash package so let me make sure if in my uh yeah so here also it's correct package config right so yeah so we have google bookstore slash package slash routes so we need the routes here like i said and now you know that inside uh a main dot go file you always have funk main so let's create the function which will basically have mux dot new router so we're creating an r variable with which will initialize the router here and we'll say routes dot register register bookstore routes and we'll pass r to it so if you remember in our routes we have some a function called as register bookstore routes here it is registered bookstore routes and we are passing the router to it r which is the router that we just created inside main.go file we are passing it to it and then we are handling the functions using as you know controllers functions right so the r that we are passing here becomes router right which is of type mux dot router so i hope everything makes sense now if there was a confusion earlier that i'm sure everything is making a lot of sense now so http dot handle comma r right and then you say log dot fatal so like since this is a slightly big project in terms of different files and project structure so i uh you know it's very important to know what's the order in which you want to build the files right so if if i would go in the order that's comfortable to me then you might get confused and so that's why i'm having to pick an order which i will make a lot of sense to you right so you'll have listen and so which helps us create the server in the first place right and these brackets i'll say localhost nine zero one zero and comma r so uh by now i'm sure you know that listen and serve is a function that helps us create a server and we pass to it this which is uh the the post port or the address on which that we want to start the server and it's inside the http package which we have here right so and if there's an error it's going to say log it's going to just log it out right so that's our main.go file now let's come back to our models file which is book.go so uh i'm going to start creating all the functions that i need to talk to my database uh things might look very i won't say very what things might might look a little confusing to you right now but when we stop when we finish writing our book controller file it will make a lot of sense to you so the routes from the routes the data uh you know the control goes to the controllers like i said and the controllers there will be different functions that i've shown you in the diagram that will have uh like you know create book and get booked by id get books right uh all of those functions will be there and then those functions will again to in order to connect with the database not to you know uh make changes in the database they have to go through these models right so we we have to write these model functions and that's what i'm creating right now out here we can do this like i said after we create the controllers as well but it may get confusing for you so that's why i want to you know write these right now so we'll have a create book function and we have something called as a db right which we have created here on top db so db is what helps us to talk to the database so db.new record now new record is a function that exists inside garm that's why we're using god because we don't have to write those queries for uh mysql the query part gordon will write which is an orm which helps us to talk to uh the database we have to write these simple functions like create a new record those kind of things right so we'll say dv dot create ampersand b right where b is something that we'll receive which will be uh of type book right and what we're going to return is also of type book so that's why we have a star book here so we are going to return b of type book right so we receive something of type book which is b so we create that and then we also return that same book that we created so that's why we have star book out here as well now i want to create the get all books function that will help me clear all books so return all the books that i have in my database and here we'll have books now i'm using a slice here because i want to return a slice or a list of the books that i have in my database right so we'll create a variable which is books which is of type slice book where b is capital just make sure b is capital and then all you have to do is db dot find books and then you return books right so you'll be returning the list of books which is slice right now i want to create a function for getting a book by id so that means it needs to take an id first obviously that's very clear which will be of n64 there's no space between ninten64 my bad and so these two things have written star book and start start gom.db don't worry about that right now i'll explain to you as we go along so we have where get book of type book okay and db is equal to db dot where w is capital by the way and id equal to id right so we are basically running a where command in mysql where we are saying that where id is equal to id right then find that book find and get so not only are we going to just return uh the book that we found right now from the database but we're also going to return the db uh variable as well so that's why we have the book that we're returning get by id the book that we're returning with that particular id in our database and we're also returning the db uh variable that we had created which was of type coord dot db right and then we have a delete function func delete book id again is int 64 and there is book before it book of type book so db.where where it helps us to find the book with the id which which i've just shown you some time back question mark comma id right so uh and get get booked by id i take an id where d was small now in this case i'm taking id reduce capital and then i'll say dot delete and bracket book and then i'm just going to return the book so these are all the uh database functions i have now here there will be a big doubt for you you will be wondering why is there no update uh function why don't we have an update function because uh in this video the way update will happen uh in the controller will be that uh we'll find the the book the id that you'll send as the from the the user that the id that we'll receive so we'll find that book first and then we'll delete that particular book and then the new data that the user has sent us to be uh updated so we'll use that to update uh the book and created basically a new data so we don't have uh an update function as such in our you know models we're just going to use uh get and delete and then post create basically we're going to use a combination of those three to update a file in our database so uh it may sound uh confusing to you right now but uh once we build our controller uh file everything will make a lot of sense right so let's start building our controller so we have package controllers and then we're going to import the packages that we need so i i know that i want to use encoding slash json package and the other packages that i need i'm just making sure that the video is still recording because because you know obs obs has a lot of problems and then i want to use the fmt package because i want to print out things to the console then i have my github.com gorilla mux that i want to use dot com slash gorilla slash max that i want to use right and i want to use my net slash http package i want to use string convert package and i also want to use now i want to import my utils and my models so by both my utils and my models are inside my package folder so you know how to do that right github.com go book store slash pkg slash utils right and com then uphill slash go book store slash pkg slash models so i have both my utils and my models right now we'll create new book which is a variable of type models dot book right so in in our model file which is book dot go we have created a struct of type book right and that's what we have been using all this file so uh of type book is what we are creating here we're creating a new book of type book right so model when i say model i'm referring to uh the models sorry with an s i'm referring to my models file and i'm referring to the struct inside uh the book struck book call inside inside my models file right so new book is of type book which is a struct and which has all these different things it has a name and author and publication right and it's called new book i'm explaining to you uh this slowly because controllers is where people get confused right so first uh yeah so here we have our five functions which is get books and create book and get booked by id and update and delete so the strategy that we'll follow here will be that we'll create the get books function first because that's the most easy in my uh x in my you know from my perspective at least uh from you know at least what i think is the get books function is the easiest so we'll build that first so whenever you're building a function a controller function you know that you have two things you have a response writer and a request for request you put a pointer to the request that you receive from the user and then so we have a request in r and our response in w so whenever uh the response that we'll send to the user will be with w so we'll have to return w basically and then we'll have new books models dot get all books now uh the model functions may not have made any sense to you but here it will make sense because what we're trying to do here is uh we have uh you know new books and in that we'll store models dot get all books so models dot get all books is this function that we just created together model.getallbooks right which will just basically find all the books and send a list of the books back to the user right so now back in our books controller we have a list of books inside new books and then we want to have a response json dot marshall new books so we want to convert it into json right whatever we see from our database so that's why i use the marshall function and then we'll use in the header we want to say content type comma json w dot right header http dot status okay okay so basically it will give us a 200 status okay means it gives us a uh 200 and then we say w dot right which is the main thing now which uh you know helps us to send something to the front end or to postman which is the response the response is basically a json version of new books that we found from the database so we're just going to write a response which will basically json right and the list of the books that we found in our database that's all it is and now the second easy function in my opinion is get booked by id so let's create that as well so funk get book by id w http dot response writer and comma r http dot request all right so we'll get access to our r which is our uh request right so inside our request obviously will be the book id right so we want to access our request and we want to access the book id inside our request so book id is equal to vars and book id so we'll have string conversion dot parse paint book id comma zero comma zero so we just want to make sure that the book id that we've received that could be in string right mostly it's a string and we're just passing it to int using the string conversion package that we have imported here and if there is an error error not equal to nil we'll have fmt dot print ln error while parsing that's what we'll return and then we'll have book details comma the blank character and say models dot get book by id and id right so we are getting get uh booked by id models.getbookbiod right which is a function that we created together if we remember let me take you to the models file and show you so inside the model file inside book.gov we have get book by id so we will be returning two different things like you know we'll be doing the book and we'll be returning the db uh variable right and since i don't want to use that use the db variable right now so that's why i'm using the blank uh character here because i don't want to use it in golang if you don't want to use something uh it's better not it's better to use the blank character because if you define something and don't use it golang is going to give you a big error so just make sure you use the blank character here right so uh yeah so i'm going to get booked by id i'm going to get that inside my book details uh variable right and now i want to start thinking about the response that i want to send to my user which will be very simple it will be just json.marshall and book details so to my user i have to send a json response right because i get something from my database i have to convert it into json and then i want to send that to my user right so that's why i have to marshal it into json so now let's start creating my header that i want to set and will be of type content type give type json and w dot write header http dot status okay and then you have your w dot write response okay so i hope this is making sense till now so inside our right header uh we are sending status okay which is 200 that everything worked fine and we are sending the response and inside the response inside rds which is the response we just have a json version of the book details basically the book that we found in the database based on the id right so i am sure all of all of that is making sense if things are not making sense to you then you just you know watch this video slower or you just type it out with me just quote it quote along with me i hope you're coding along but maybe once more you can code long and then uh you know things will start looking becoming clearer to you and if you still don't understand then you can just you know put a comment in the description in the comment box below uh for the video and then i can probably help you out so you have your response writer comma r is your http dot request so this is a quite long video right so if you've reached this far then you should be really proud of yourself model stock book all right so utils dot parse body now we'll receive something from the user right as a request and now we want to pass that uh into uh so we're getting that in json we want to pass that into something that our database will understand so that's why we are using parse body which is a function that we created together inside the utils file right so we're going to say r comma create book all right and then we'll say b is equal to create dot create book so create book right is a model of type uh is a model uh inside the models you have books right so create book is of type that basically and then when we say create book dot create book so i'm referring to the create book function here this one that's what i'm referring to out here okay so we'll have create book.trade work and then i'm gonna i now have to start thinking about my response my response will be json.marshall inside that i passed b so b is something that was returned to me by my create book function inside models let's look at what it's returning to us so it's returning to me the same model that is the same object or same it just created inside the database so it created something inside the database and it's just returning to me the same exact thing so that's what i have access to which is b in this case so it's basically the same book that was sent to me by my uh user as a request right so in the response i'm just going to convert that into json so from uh in the beginning we received json and then we passed it into something that the database would understand we sent it to the database the database sent us that same uh you know record and then that record we are converting that into json right now to be able to send that to our user to postman basically so we'll say w dot write header and then we'll say http dot status okay w dot right and we're just going to write our response to the uh postman right so create book was also uh i feel quite straightforward now we'll work on the delete book function func delete book so which will have w http dot so let me just check if the video is still recording i'm not sure yeah it seems like it's still recording anyhow so in our delete book uh function so as you are seeing right now that all of these functions are talking to another function inside our models right so same similarly with delete book we'll be talking to the delete book function inside our model which is book.go so let's have responsewriter and comma r which will have a pointer to the http dot request that you'll get from the user and then we'll use vars again to be able to uh you know access the request that we've received from the user and now we want to access the book id where's both id right and then we have our error so string convert so basically if you're not understood by now this we're doing the exact same step that we were uh doing in the get book by id so because we need uh to access the request then we need to access the book id then we need to convert that into hint which will uh you know do by string convert.parse and package and then we'll also print out the error if there was some error right while passing so we're doing the exact same thing steps there's nothing new here parse hint and book id comma 0 comma 0 and if there is an error which means if error is not equal to nil then we'll say fmt dot brain talon and here we'll say error while parsing all right so that's great till now and then we'll have book is equal to model start delete book id so you know this function write delete book which we have created together in the models file delete book it takes an id and it just deletes the book and then returns the book that it just deleted right so the book that has been just returned to us will be inside the book variable all right now we have to start thinking about the response and how we have to send it to our user inside postman so we'll say json.marshall the book that we received from our database function right now that needs to be converted into json so and now we'll start creating our header and we'll setting set or header content type comma pkg location slash json w start right write header http dot status okay w dot right and this is the response the last three steps are the same for almost all functions there's nothing new there now there's only one function left to go which has obviously the people find it the most complicated function which will be the update function and it will have some aspects of all of the different functions that we have seen till now it's also the biggest function so update book is the biggest function and uh let's get started i mean that's why i always covered the update function at the end because it can be confusing to people so that's why we have already seen delete book create book get booked by id and it will just have a combination of all of these functions right so let's create the update book function where u is capital and b is capital w http dot response writer comma r which will be http dot request right so i'll go till here no confusions so we have update book which is of models dot book pretty similar to our create book right the same same code we're writing out here details dot parse body so whatever you have sent in your request as the new body to be updated in the database for that same id that's what we're going to parse and we're going to take from json into a into a uh we're going to unmarshal it into a format that golang understands in the database understands so that's what we have done here now we want to get our id which is what is equal to mux dot vars so like i said so it's a mixture of the post the create book function and the get by id function right so book id let's go to vars and we get access to book id so till here uh we wrote some code from the create book function and here we have started writing some code from the get booked by id function right the same thing the same part we have to repeat here so id comma err i'm not going to copy and paste it because uh i always encourage you to write everything so that you get very very comfortable with the code right parse hint and book id comma 0 0 and if there is an error which is error not equal to nil then we're going to print out fmp dot print ln say error right right so completely the same till here right this this whole part is exactly the same and these two lines i just showed you is the same from create book so till now i think there's nothing confusing at all so now let's get the book by id right so we need to find that book if that book even exists in our database only then we'll update it right so let's find that book about details db equal to models dot get book by id and we'll pass capital id there if update book dot name is not equal to empty string it's not empty and book details start named okay so let me type all this out and then explain to you what all this means and if update book dot author is not equal to empty then book details dot author is equal to update book dot author right and then f update book dot publication is not equal to empty string then book details dot publication is equal to update book dot pub location so in our book model as you had seen there are three things right name author of application so when we have to create a new book right then while creating the new book uh you'll have to have these three fields name author and publication so we are assuming here in our controllers that the request that we'll get from the user it will have uh all these three properties name author and publication so we'll take the request that we got from the user inside update book and we have uh you know parsed it right so it should be utils dot yeah so this is a big mistake here that i've made it should be utilized parts body and not just parts make sure you update that as well right so let me check if everywhere else i have not made that anywhere else i've not made that same mistake yeah i have not so it's parts body little dot parts body and uh everything else looks to be all right okay so we are assuming that that update body after parsing has three things name author and publication so we found that uh body as we found that book from inside the database using get booked by id function because we have when whenever we pass whenever we call the update function we call we pass the id and we pass the body the new body for the new details which need to be you know set inside the database now so we'll have name author in publication and for book details right we need to start setting uh those three things so now book details is something that we get from our models get booked id so get booked by id by passing the id we get a book back in return and now we are setting the details for that particular book object right so we said book data's dot name now that will become equal to the new name that we have sent as part of the request that we had also passed right and the author will also now become equal to the author of the update book you know which is basically the request inside that we have passed an author so that will be become the new author and similarly the publication will also become the new publication so all of that detail is now inside the book details record which we now want to save in our database right so we since we have updated it now we want to just save it so updating is taking place inside our go link it's not taking place anywhere else so we just found it by id we now updated all the details and we're just going to go ahead and save it again right so dot save details now we want to send some response to our user as you know it has to be in json so we're going to send the book details which we just updated right so the updated things is going to go to the user so header and dot set content type comma pjq relation slash json then w dot write header http dot status okay and w dot write response so we've even sent the response to the user and so we have written our uh update function delete function create book get booked by id and get books so i think all of the work is complete so now let me just go between all my files and see so main.go file is complete config file is complete controller is complete models are complete routes are complete and utils are complete so all of this makes sense and now it's time to start testing and start fixing if we get any errors or bugs and also to check how to work with our of these apis in our post plan so let's head over to postman so we are back in our terminal because now we want to start trying to run that code that we have written the entire bookstore api so uh as you can see i'm inside my google bookstore folder right and it has cmd and package you can see that i want to go inside my cmd package and it has a main folder so i want to go inside my main folder this has that main.go file now main.go file is the file that we need to be able to run the go build command if you run the go build command anywhere else it won't run because it needs the main.go file now when you run go dot go uh space build i'm expecting to see a lot of errors right and uh you don't have to worry if you see the errors because that's a part and parcel of being a developer so you will have to uh you know get used to solving those errors that you get so as soon as i press go build it's going to give me some errors so right now it's giving me only one error but once i solve this error i know there will be many more errors right so right now it's saying that in book dot go file at line number 11 it cannot refer gordon dot model so i kind of know where the error is now i'm not going to edit all all of this out you're going to solve the errors with me so that you become better as a developer so you can uh you know identify so it's saying uh book.go file and at line number 11 is going to say gone dot model is not there so all i had to do was put a capital m here and now it won't give me the same error again or so i expect so if i say go build again it's giving me like i told you so this error is sorted but it has given me so many more errors right so the first error it's saying is it cannot refer to an exported name mux.vars so let's go head over to line number 47 in our go book controller line number 47 yeah so vars uh vars has to be capital v right so that's why it's not able to access so we'll say capital v and that error should at least go away right so this error will go away and then it says label book id defined and not used which is line number 64. so yes it's saying define but not used because i missed the is equal to sign here and i have a feeling that all of the other uh errors because they are much later into this same function so till line eighties here till nine number eighty from 65 to 80 i'm seeing all these errors and i have a feeling that they're all because of this is equal to sign that i've missed so now i'm going to go ahead and go build again and let's see if there are any more errors yeah so there are more errors it's saying uh go 71 3 undefined book details so let's find out so these errors are on line 71 74 77 and 79 and 80. let's look into the code what could be the issue here so 71 74 and all of these lines and the error basically saying that book details is not defined so i can see here that i've written books by mistake and not book details so once i fix that i remove that extra s hopefully these errors should go away and there could be new more errors no so there are no new errors when i ran go go build uh there were no new errors and it created this main file here for me and now i can start to uh run this code and i can start showing you uh from postman so you can say go run main dot go it it won't say anything that means that uh it's started running on your postman so now let's head over to our postman and i'll show you how to work with each of these apis that we i've opened up my postman window so postman is a tool that helps us to test all the apis if you don't know what postman is you can go ahead and watch any video from youtube and uh so what i'm going to do is i'm going to create a collection here and i'm going to call it bookstore my server is still running so inside my bookstore collection i have to create a request and i'll call it get all all right and then i have a request called create then i have get by id i'll have update and finally i'll have delete so for get all i need localhost 9010 where this project is running and slash book slash okay and if i get all i get an empty array and if this is what you get then your server is working perfectly fine you're getting the right result because right now we don't have any books so we get an empty array right and so that's why if we had don't have any books we have to create the book in the first place so we will create the book using the post uh or create right so we'll say book slash and then we'll use the post method we'll send somebody now remember in the body we have to send json and json will have three fields one is name the other is author and the third is make sure you get the spellings of author and name in publication right what is publication so name of the book is zero two one and author is peter thiel publication is penguin i think so you send it and you get a response which basically shows us that everything is fine and we get status 200 okay which we have only sent we wrote it right in the code that is that header status okay and let's create another book let's call it startup way by eric rice and i don't know what the name of the publication is so i've created two different books by the way both of these books are amazing if you're planning to start your own company i highly recommend you read these books and so you when we run the get all uh api again it works perfectly fine right we get both the books that are there in our database and now let's get by id so we have one book with id3 and we get that zero to one and one book with id4 and we get that as well perfect now we'll update the book by which which has the id4 and for the body i'm going to again select raw json and i'm going to simply copy and paste this here and let's change the publication to orion so it's updated the book and now the publication should have been oh sorry i have to read put here the publication will become orion right so don't forget to change the methods here right and for create the method was post and for update it is put right i hope that makes sense now we can go ahead and delete this book and for that i'll need the delete method in my postman when i send that you know the book is gone hopefully so now there's only one book remain which is which has an id3 which is basically zero to one by beta theta so all our five apis working perfectly fine and if you have completed this video and you have been able to uh code out till this far uh congratulations in this video we're building something very interesting we're building a slack bot that calculates age uh using golang without any delays let's get started so uh the prerequisites to this video are that you should have a slack account right obviously that's how you'll build a slack bot right so you should have a slack account you should have a workspace in your slack and you should be the admin of that workspace only then uh you'll be able to build a bot right in slack and then you have to come to this link api.slack.com apps and this is where we'll be able to start our apps so i'll say create new app and ask me two different questions from scratch or from an app manifest so in this case i'll be building and building a bot from scratch i'll call it the agebot right and i'll give it my workspace and now uh we have to find socket mode on the left is the third button on the left right socket mode and we have to enable it and we'll call it socket token so this will generate an app token for us x app so when it says xapp it is your app token and it says xob it's your bot token right x2 xb it'll be your bot token so you can make a note of this you can copy this i won't copy it right now i'll come back for it later on in the video uh so this is your that was your app token and now let's go for our uh event subscriptions which is the third uh button so the fourth button from the from the last right and we have to enable our event subscriptions we have to subscribe to what events and uh let's add some events right so events are basically uh that or something that our bot uh would be subscribed to so these are socket events so i'll say app mentioned whenever somebody mentions my bot and i'll say message history and i'll say message.im right it can read messages and then messages.channel messages.mpim right so these are the uh events that i think my bot uh would need to be subscribed to uh but then there's always you can always come back and tweak them later on if you by mistake if you leave out any and you can always uh you know this is mostly uh you'll get these by trial and error right so i've built more than 50 slack bots so i know and and this is a tip for you as well that it's always better to add more events than less because and and also now uh what we'll do is we'll add uh oauths and permissions so come to this uh option above event subscriptions so oauth and permissions also you have to add some uh permissions like scopes to your uh bot uh these are very similar to your event subscriptions so here also it's always recommended uh with even subscription and with uh oauth information it's recommended that you add more than you need because uh most of the errors that you'll face when building slack bots would be around uh your bot not having enough permissions or authorizations or authentication you know those will be the kind of errors that you'll face so it's better to always uh you know add these so that you don't have to like deal with a lot of errors right later on so i'll just add some regarding chat right and uh let's say channels read right and then say um i am read and i am right these are the items are basically direct messages mp i am read and npm right also i'll add right and i don't think i need any more um permissions for now but if i have any errors then i'll come back here and i'll add those permissions right and now the problem with building slack boxes sometimes they that you don't even get an error and your ad you're uh you know doesn't respond properly or and it doesn't give you the behavior that you're expecting it to give you and and those problems are mostly revolving around scopes right so there are so many errors on stack overflow when you go and you won't find answers to those problems because uh those most of them are around scopes those aren't even errors like people would be saying my slack bot isn't working and those kind of issues right so those are all around scopes i can tell you that from experience anyhow what we'll do now is we'll actually click on install this to workspace and it'll ask me for some permissions i'll say allow so that means now age bot is uh installed to my workspace and it has given me a bot user oauth token right so i need to make a copy of this as well uh so now what we'll do is since we have our credentials in place now it's time to actually start uh building the bot in golang right so i'm in my uh directory where i keep most of my golan code and i'm going to create a directory for this particular project called slack age bot sorry for the wrong spelling of age and i'm going to go inside directory and here what i'm going to say is i'm going to go mod init github dot com slash uphill slash slack i'll say um slack age bot is the name of the project so this is an absolute link that helps me to import other files in my project and in this project particular project we don't have multiple files we are going to only get to have the main.go file but if this was a bigger project then this would have been very very uh helpful and also using github.com uh you know helps helps a lot because later on if you have to push this to github and then use it as a package in your own project later on or somebody else has to use it as a package in their project it's very very useful so this is the best practice uh you can always innit your go programs like this so we'll init and it is taking some time i don't know why okay that's done and there is one uh external package that we need so i have to run the go get command and the package that i need is github.com shoma lee one one slash slacker all right and uh just to be sure i'll say go mod tidy okay and so we have added the the package that you want so if we ls right now we'll see our go modern go some file which is perfect which is exactly what you want so now what we'll do is we'll open up our code editor which is uh vs code in our case in my case uh you can have any other code editor that you want but vs code works best for me so i'm going to use obvious code and now we'll start writing our code as you know uh the main file in a go program is called main.go and the first thing that you have to write is package main then you have to import some packages i know that i'll be needing the context package i know i'll be needing fmt to print out stuff and log is something that i'll be needing i'll be needing os package and the most important thing that i'll be needing is the external package that i installed right so i'll say show molly11 now if you're uh yeah so if you're uh coming from a javascript background so what i did there with goget command is simply uh you know uh npm installer it's it's exactly equivalent so it creates uh those entries in your go modern go some file which is almost like your if you're from a flutter background it's almost like a pub spec yaml file or popsicle dot log file and if you're from a uh node.js background it's from it's like a uh you know package.json and package.json.log files you know that's what these are it's very very similar concept right and uh so what we're doing here is we are going to uh write our main function funk main and in funk main i'm going to set my environments right so i'll say uh now you can you know set your environment in an env file but i'm not going to do that i'm just going to uh you know use my os uh package to actually set environments and i'll say slack bot token okay comma and here i need to copy and paste my slack bot token and then i'll say set environment slack app token right so far so good and now what i'll do is i'll just uh go ahead and get my tokens from the slack uh this is my bot token so i'll copy this and i'll paste it here this is my what token all right and here is my yeah i'll and to find my main token i have to come here this is the socket token that we created that is our the xapp one that is our main app token so i'll say i'll copy and paste that here as well so far so good and now we have to create a bot right so we'll say bought an assignment operator or the walrus operator whatever you want to call it slacker dot new client and we'll say os dot get paid environment this is slack port token and we will say comma os dot get environment slack app tool now uh you don't have to have uh you know set environment get environment you can directly pass the tokens here directly right inside the new client uh function but why i'm doing this is because this makes your program more extensible so later on when you have to extend your program and uh you you have those environment files or you have a production environment where you have these tokens or you're using some program that manages all your credentials then this comes in very handy so i'm just getting you in the habit of you know going the right way from the beginning so here we'll start to go routine which will uh it doesn't do any much it just prints uh command events so we'll say command events by command events i mean uh the e like let's say whenever i pass a command to my slack bot uh so whatever it does or whatever the the way it handles the event at the event itself it's going to print it out right so this means that print command events needs to be a function which we have not created right now so let's create that function so we'll say func print command events and we'll say analytics channel and chan creates a channel and we'll say slacker dot command event which basically we're passing here right and here we'll say for event we're going to arrange over the analytics event analysis channel and we're going to print out a couple of things so we're going to print out the timestamp as in when the command was received by slack right and the command itself and the parameters that we have passed to that command and the event right so let's get started so we'll say print ln and here i'll say command events and then i'll say fmt dot println and i'll say event dot timestamp like i said we need the timestamp fmp dot rent ln event dot command and fmt dot print ln by the way all of this is uh totally optional you don't have to do all this like i'm printing out uh in my console whenever any event takes place uh in my program but you don't have to do this given dot event and then just an empty line we'll put them into line print ln okay so far so good now comes the real uh function the most important function but before that we need to write some code to actually stop our bot cdx cancel context start with cancel and context dot background if you're a golang beginner i'm sure you already know what context does and what differ is differ basically make sure that uh the cancel uh is you know uh all like played or or this function is called towards the end like when this function is about to end right so that's what therefore does and error is equal to bot.listen your bottle listen to the context if there is an error which means if error is not equal to null you're going to log out the fatal log.fatal fatal is a function that logs out the error so we have used our log package that we had here we've used our os package to set the environments we've used our fnd package to print out stuff and all we need to do now is use the slacker package right uh now let's create the program that we need to create so that program is bot.com so we have the what we've created the bot here right and here we need to say bot dot command so this is where the magic is happening my year of birth is and you pass a parameter inside here so this with these two uh angular brackets is the parameter and you'll say ampersand slacker dot command definition and this is the description of the command so we'll say you know iob calculator and just give an example sorry example my is here 2020 all right so this is an example and then we give it a handler so handler is where we handle this uh event using a function which takes the bot context slacker dot dot context and we pass it the request so as if whenever we have any functions that uh you know work with http kind of data or socket data you know you have to have request and response right and request will be slacker dot request and response will be slacker which is the package again dot response writer so uh slacker dot request lack of dos is responsible we are using the slacker package here all right so everything makes sense till now i hope everything makes sense to know it's giving us one error i don't know where the error is but anyhow so let's create this error so we'll say here is equal to request dot param here so whatever here has been passed so when the user says my yob is here this uh param uh we'll get into a variable call here right now using this and then we'll have a variable called yob so we'll say string convert dot ato i here we'll convert into here so now this means that i need another package called string convert because this is not native to golang this is a this is a package in the golang library right so we have to get string convert as well uh so uh so far so good so we have our here in yob and then if error not equal to nil we'll say print ln error okay and then we'll say age not equal to sorry a is equal to 2 0 2 1 minus y to calculate h all you have to do is year of birth has to be subtracted from the current here that's going on right now it's 2021. if you didn't do this right if you don't use string convert and atoi function you would have this uh in a string format and you won't be able to subtract it here golang won't allow it so to have a number of took uh to get a number from string you have to do this and only then you can perform a subtraction operation right because golang is a statically typed uh language you can't subtract a string and a sprinter and an end so we'll say sprint f which formats our string for us age is percentage d comma h we'll say response dot reply r so in age we store 21 minus yob which is the edge and then we format it out like this with this text and then we reply this now i'm getting two errors one is this so we don't have this package it's saying somali double one we should have had it because we added it um i did add it actually so let me say again go get github.com slash somali one one slash slacker it says it has added this package then i don't know why my uh vs code is acting up and then uh it doesn't seem to have any more errors this is the only error that says uh there is there could be an issue with the spelling though i mean uh now there's no squiggly line so everything seems to be all right um and then it's giving me a red squiggly line out here i don't know why let me check so it says bought command okay yes so my mistake uh this function definition we can't close it out here this needs to be closed somewhere out here and here there needs to be comma now uh there shouldn't be an error now and yes spelling of command events is wrong so i've collected that as well now it's a question about of i think counting these brackets so i'm just going through it again i have written the description i have the command line the description and there's the example there's the handler func uh request response then i have the year then i have iob uh print line age 21 sprint f response reply everything seems to be all right to me but uh it seems there's still one error right so it says in the even dot parameters there's an issue yeah that's because the spelling of parameters is wrong and now as you can see we don't have any issues i'm using a golang plugin that helps me to find these errors without actually running the code so which is very helpful now what we'll do is we'll say go build to see if there are any errors there there seem to be no errors it has created the dot apc file for us and uh what we'll do now is we'll head over to our uh slack channel and here we will uh be expecting our bot once uh we start the bot right we start the program and so let's do that let's actually start our program so go run main.go so it says connected to slack with socket mode that means everything should be fine and so here i'll say agebot and i'll say agebot my yob is 1990. so it says the slackward says that you mentioned each board but they're not in this channel so i'll say invite them and then uh agebot automatically replies age 31 awesome right so you'll say age bot my y o b is 1995 let's say age 26 isn't that awesome so i hope you learned a lot in this video and uh you were able to uh you know understand how to actually apply your golang skills and how to build a slack bot right and how to get the tokens from slack how to add those permissions and how to enable socket mode all of those things are really important in building a slack watch and also this kind of function and the package that we've used slacker right that makes making a slack bot really easy in this video we're building something very interesting we're building a slack bot that can upload files on a slack channel right so the prerequisites are that you need to have a slack account obviously and you need to be the admin of a workspace basically on slack and then you have to come to api.slack.com apps now if you have built slack bots before and you just want to know about how to upload files then you can skip the part where you know i'll show on how to uh get your bot token and your app token and you can skip directly to the part where uh we start working with golank or otherwise you can stick around and see how we need the we can get the bottom right so uh we're on api.com apps we'll create new app from scratch i'll call it filebot and the workspace is worldtech create now i need socket to be enabled so i'll click on socket mode the third option i'll enable it and i'll call this token the socket token generate so let's generate a token for me and i don't need this token for this video i just need the uh what token in this video so what we'll do now is we'll actually go to even subscriptions and we'll just enable it as well even though we won't be using events in this video but we'll just enable it anyways and then we'll go to our oauth and permissions all right so let's give it some scopes so obviously we need to be able to uh read messages so let's i'll just say chat write and channels read and then i need files read and files right and i'll also say i am reading i am right now uh if you've watched my other videos on how to build slack bots the other videos then you know that i always recommend going for more scopes than you need because a lot of the errors on slack stack overflow around slack bots have been caused because because of authorization authentication and permissions issues right and they all revolve around the scopes so it's always uh good to have more scopes than you think you would need because sometimes the slack bots don't even give you errors so that can be very frustrating sometimes right so we'll have remote files read and remote files share and write also i'll take those as well so remote files sorry not remind us right but remote files the remote files right and share okay now most of these we may not even use but we are still like i said you know you're still keeping them so we have all these uh scopes and it might so happen that we uh you know um we might need to add more uh depending on if our bot is able to perform the actions that we're expecting it to uh perform so it's asking me for some permissions i'll allow it okay and now you have your slack watercolor i won't copy it right now but i'll come back for it all right and uh the other thing that you would need is your slack channel id on which you would interact with your file bot and i'll show you that as well all right so now what we'll do is we'll head over to our powershell or uh you could be on your mac terminal or ubuntu terminal doesn't matter the commands will be the same all right so i'm in the in the folder where i keep most of my column code and what i'll do here is i'll create a directory called slack file port all right and i'll cd into slack file bot and i'll go mod in it and slap file what this is my absolute link if you if you're very new to golang this is your absolute link with the help of which you'll be able to uh refer refer other files in your project in this project particular project we are going to have only one file main.go but if this was a much larger project uh then we would have to uh you know write multiple files and github.com because once you upload your project to github you might want to use it as a package in your other projects right so it's always a good practice to have your absolute link like set up like this so this is a good practice we'll go mod in it and it has created a go mod file so if ls you'll be able to see your go mod file right and then uh you need a an external package to be able to work with slack so we are going to import that now if you're from a javascript background you would recognize this as your npm in it and you would recognize this as your npm install so don't we are just installing an external package so we will call it github.com right so this person uh just like us this person had given github.com link so that you know now we are able to access his library very easily into our project so we will get that so it has hopefully added the slack go slash package and what we'll do is just to be sure we'll also run go mod id and says all match no packages no issues everything works perfectly and now what we'll do is we'll open up our code editor so i'm using this code you could be using any other collateral no problem and just another pointer i'm also using a golang plugin in my vs code that helps me write better code so i'll leave the name of that in the description box below but even if you just search for extensions uh golang extension you'll find it it's not it's not something very rare everybody uses it so we are in our vs code and i've opened up a file called main.go which is uh what the main file in golang program is called in case you're new to golan the first thing that you write in a golang program is package main and then you import some libraries and then you have something called respond right so these are the things that are uh the most important in a golang program and uh i know that i'll be needing fmp to print out stuff so the format package has uh things that are required to print out stuff to the terminal then i know i need the os package to set and get my environments and i know that i need the external package that i just installed called slackgo to help me talk to the slack apis right now slack go is a rapid library that somebody has written around the slack apis in golang so that we can call uh the funk the golang the slack apis as functions rather than as actual api so we don't have to make network requests to the slack api because somebody has already written wrapper functions around it and we just have to call those functions uh using this library right so that makes our job extremely easy and then you can uh create a variable called api and it will have slack dot name so using this package now slack and we're creating a new connection we are calling it and here we will get uh you know uh something from our environment and it will basically be our slack token now uh ideally you would have an environment file right or if you're in production environment you would have uh that those the environment set up to have these variables but since we don't have it set up what we'll do is we'll actually set our environment right now using the set env you don't have to do it you can directly pass your bot token here but i do this because this makes the code uh very extensible and you can extend it later on if you in case you want to go to production uh like i said we don't want to go to production right now but if you wanted to you could because we're keeping everything uh modular right so uh here we'll put at what token and also one more thing that i need uh like i said is the channel id on which uh the bot will be able to uh write the upload the file okay so here i'll have something called as channel uh and this will be my channel basically it's also string and os dot get environment inside that we'll have our channel id all right and then i'll have my file file arr string and here i'll put the name of my file you know whatever i wanted to be so now let's go back to our uh google chrome and get our slack bot token and channel ids so slack bot tokens this is my bot token so i'll copy it and i'll paste it here okay and now we'll have our channel id and i need to get to my channel id so this i wanted to post it out also on the general channel so i'll say i'll right click on the general channels i'll say open channel details then towards the end you'll find the channel id which is this okay and then i'll go back here and i'll paste it here makes sense so now we have set our environment for our slack buttock and slack and channel id and we uh sorry yeah and then we have our uh you know uh variables api channel and file which have the api connection with slack and then uh the channel and then the file that will be sending out uploading basically and now we'll create a for loop so uh right now we have only we'll have only one file here but we could have multiple files right so we have to uh go over all of the files that exist in this variable in the slice right so in the slice all the files that are there we'll say i plus plus and say programs slack dot file upload parameters so this is a function that slack gives us and it will have two parameters okay and we'll take that into of our own variable called params so the two parameters are channels where i'll pass the channel in which i want to upload the file and i'll pass the file itself which will in this case be file a r i right because we are looping over file arr which uh in the for the sake of this video will have only one file but you could have multiple file here files here like hundreds of files and then you could loop over them and then you could uh you know send them here all right so put a comma here because it's giving me some formatting errors so i'll say api dot upload file with the params all right so i have my param set here with channel and file and i'm going to call the function called upload file uh in my connection the slack api right and i'm going to uh take that into a variable called file or it's going to return an error to me and so i'll check for the error so if error is not equal to nil that means there is an error i'll print it print out fmt dot printf i'll say percentage s new line comma error all right and we'll save it on and then we'll print out the name and url of the file so let's say name percentage s url percentage s new line so this is a very short simple program and even though i've added slack i don't know why it's giving me shoes i don't know why there's a squiggly line and shows one error even though i had actually got my import the package so this sounds this looks a bit off to me uh but yeah everything else in the program looks okay to me where uh let me just go through it again so that uh you know we're able to minimize uh the errors so there's the channel id and slack dot new slack oh yeah so here we have to just uh pass the file so you can copy any file that you want and i'm going to just copy and paste a file called zipl uh dot pdf all right so i'm going to pass here is that apple.pdf but you could have any file out there and after that everything else looks pretty all right to me so i don't know why there's a squiggly line here even though i've installed the package what i'll do is i'll again run go get github accounts like slash slack so i'll again add it and now hopefully the error should go i'm not sure yeah now it's gone weird right anyways so let's uh run our code let's build our code at least to see if there are any errors in runtime there are no errors so we will say go run main dot go and at the same time we have to keep our slack channel open right so here in the general channel is where i'm expecting the file to come up right so i'll say go run main dot co and let me head over to my slack channel and see if the file comes here i don't see the file yet says not in channel so this looks like an error to me uh and i'm pretty sure it has something to do with the permission so let me uh go over to my uh slack terminal and slack dashboard and see what these so back in my slack dashboard or my channel i think the issue could be that the file bot is not part of the channel right so what i'll do is i'll try mentioning filebot and so it says want to add this question instead isn't in general yet so i'll say add to channel so file bot was added by kil sharma and now what we'll do is we'll run our code again and see what happens and let's go back see it was able to add the file it was able to upload the file so it works perfectly so you'll have to add your file bot to the channel before it can start pushing files to this channel right and if you see this error it's not very helpful right so it's not in channel i mean what the hell does that mean and i've uh you know had so many errors in the past like i've built more than 50 slack bots like are there on production on you can get them on the app store at the slack app store uh marketplace and then uh the thing is it's so frustrating to build a slackbot because most of the time the errors are around like i told you the scopes right and uh because you're trying to do something and you don't have that particular scope selected and then it won't even give you the right error it'll just say uh you don't have uh the authorization or you don't have the permission something like that but it won't tell you uh what permission you don't have so it can get really confusing so just make sure you add more scopes than you need and whatever scopes you think you might need you can obviously add them and don't be shy and just add as many scopes as possible just add all of them probably you know it's not like you're going to share your tokens with anybody else right uh like delete so for example i just made this uh test uh uh app i'll just delete this uh what after uh the video is over and uh now if you're going to into production obviously if you're launching a slack bot to the marketplace then obviously you need to think about what are the exact scopes that you need and you can remove the ones that you don't need to make it more secure but otherwise while testing it while learning go ahead and do whatever you want right in this video we're doing something really interesting we are building an email verifier tool so if you search for email verifier tool on google you get all these different options right hunter dot io snow dot io zero bounce never bounce and all these tools like let's say if you open up snow bio and if you open up email address verifier all these tools are quite expensive and some of some of them even say that well didn't check in real time right uh they try to sound really fancy but what's happening here is really straightforward it's there's nothing fancy happening there only in some tools like let's say um hunter dot io they use a little bit of machine learning here and there to uh you know determine uh basically to make the tool even better and more enhanced but otherwise most of them are just using very simple uh tools to uh create an email verify tool so if you wanted to you could uh simply take this program that we'll build right now and you can just launch your own email wi-fi tool if you want to i mean completely optional all right so we'll use golang nothing fancy we won't have bulk uh verification um ability right now in this program it's very simple you can extend this the functionality of this program to include bulk uh checking as well and in the future uh a few weeks from now i'll actually build a complete uh you know like a complete solution for email verification all right so this is just a precursor this is a very simple program that you're building right now but a few weeks from now i'll build a complete project around it all right where you can uh also do bulk checking and you know there'll be a more there'll be a few more checks right now we're doing a couple of checks but there will be few more checks all right so let me show you how the program is going to work i am now in my terminal and what i'll do is i'll start the program and mind you this program is super simple so it won't take us more than 20 25 minutes to actually build this whole thing right it's very very straightforward so if you go down main.go it shows you these options it says that when you uh enter a domain name right now it will give you the domain names name and will check for mx records spf records if it has any fcf records if it does then we'll give you the spf records if it has any demarc records and we'll give you the democratic calls all right and by checking these then we'll know uh if the domain is at least right from which that email id is come out from to which you have to send the emails to right you'll just check the domain if the it even has any imax records so that's like the first stage the first check of any email looking up or any email verification that checking if that domain name even has an mx recorder an spf record as a democrat record right so that you can know at least you know there are mx servers set up there a mail server set up there all right so uh here let's say you write mailchimp dot com so this is like uh irony because these guys uh help people send emails and we are building a tool using their website to check if they have any valid uh you know email records so let's enter that it'll take a while because mailchimp has done a lot of clever things to uh you know not respond straight in a straightforward manner so i'll say that uh the request has timed out right it says uh this operation returned because the timeout period expired but it'll give you still give you the right records it'll give you mailchimp.com which is the domain does it have a mx record that says yes true it does does it have spf records false so that means spf records uh there's you can see this there's a blank here that means uh since there's no spf records it won't return the spf records obviously does it have dmarc it'll say true and demarcus records this these are the mark records all right so now you know that mailchimp.com is a valid email people it's like emails have been set up on this record and now you can start looking for the names of the people and then actually finding email addresses of those people if you wanted to right like i said a few weeks down the line we'll build the entire product right now we're just building like uh you know just telling people if the the email is real or not just like something like uh you know this this tool out here called email hippo you write something like you know akil at the rate mailchimp.com and the first thing is going to check is what we just checked right now does it have mx records uh spf records or dmacc records if it doesn't we'll just say that this email address is not valid obviously because the domain itself is not valid right the one itself does not have any mx record setup but here in this case it'll say true because in our case also it returned true so i'm not sure if this is yeah so it's saying the result is bad because yes the email address does not exist but uh probably it's saying that this exists but this email on this this person on this domain does not exist something like that right so anyways so you get the picture of what we're building and now let's start building it like i said there's no external library used here we're just using like the basic golang packages that you get so if you know even basic golang if you just completed the golang tour if even if you don't know that actually uh you can you can still complete this project so this is like a you know simple uh like a beginner level project so feel free to follow along with me all right now since this is a beginner level project i won't explain a lot of things there's not much to explain anyways i won't explain a lot of things uh feel free to code along with me if you don't understand anything look it up on the internet or put it in the comments below i'm always there to help you out right but it'll be really simple right so it's i mean there's nothing complicated here we're not using go routines we're not using channels we're not using even structs we're not using uh interfaces nothing like that it's just like plain simple colang all right so let's get started what i now want you to do is open up your new terminal and traverse to the path where you usually keep your golang code and create a new directory let's say like email checker tool cd into it and open up using your favorite code editor in my case it's vs code and here there's not much in this project right it's just main.go so you'll start with package main you'll import some things obviously we'll talk about them in a while and then there's yours there's your uh funk main right the most important function in any golang program funk main basically calls another program called funk check domain all right and this function just takes in a domain so essentially all you're entering uh that you just saw in the demo or you're entering is the domain name right so that domain name basically gets passed passed from our uh terminal using funk main something we'll write in our funk main we'll pass it and we'll just push it or send it to our check domain function which will do all the magic all right the packages that i need here i need buffalo the buffer package to to be able to parse whatever i put in the terminal i need fmt to print out stuff log as well need a net package to make those requests os and strings once we use these packages it will make more sense to you why we're using it so firstly you'll create a variable called scanner and you'll use the buffer package and there's a function called new scanner that you'll use okay and here you'll say printf and the things that we're printing out when the program started will be basically domain has mx has spf and if it has spf then it'll show you the spf records then we'll check it has the mark and then we'll check for the mark record okay so if you remember when we started the program it just showed us these things so that we come to know in the order which will in which the information will be shown to us okay so it's exactly the same thing and now for you to scan the information you'll use scanner.scan function and you'll so let's say there are multiple items to be scanned you'll now i i know i said that there's no no bulk uploading uh as in bulk checking but you can check like a few uh you know emails but when i say bulk uh checking i mean like like uploading big csvs of thousands of records and then checking them in one go right that's what we don't have but like multiple checking is there all right i hope that makes sense so you have scanner dot text so uh whatever was typed by you in the power shell or in the terminal is now basically sent to the check domain function one by one so multiple domains if you know if you want to or it's just a single domain mostly i have tested only on single domain so please um if you know there's a there are problems working with multiple domains then uh you know it's only because i've not tested it i've just associated with a single single domain so start the program and just put a single domain like mailchimp.com like i showed you in the demo so it just works perfectly fine for that i've tested only for that and then we have like i said this is not a production level software right i said like you can put it on your website as a small simple free email checker tool but don't like charge people for it because you don't have uh the complete architecture required for it to be a complete production software right i hope that's clear because i i get strange uh comments sometimes so that's why i just you know clarify all these things so to um log out the error now if there's an error obviously uh then we're just logging out the error so the error is could not read from input comma error so if you notice all that we have done in the funk main is just pick up or scan the user's input from the terminal all right the domain name that you've put and if it's not able to scan it properly whatever domain name that you put is going to say could not read from input right it's going to print out an error and what we are sending to this check domain function is the text and that whatever you've posted in the terminal and now the check domain is the is the part where which is basically the meat of this entire program because this function will have all the logic required to actually check those records okay so firstly we'll define some variables the first variable will be has mx has spf has d mark all of these are boolean then we'll have the spf record i mean if it has an spf record then we'll show the spf record right like in our case when we uh did a demo with mailchimp there was uh this was false so that's why we didn't have any spf record it was blank and if there's an uh dmark tool like we had did for mailchimp we had democtool we'll have remark record here and it'll be a string all right now we'll all be doing here basically is using the net package to firstly look up the mx so the net package already gives you um the ability to look up the mx of the domain that you just sent here domain is that string that you're passing to this function all right and whatever comes back from this function we captured in a variable called mx records and this function if there's anything that goes wrong will also return an error and now you're getting these quickly lines because you've defined all these variables but you've not used it right so what we'll do now is we'll say if error not equal to nil this error basically will handle on this line log dot printf error percentage v comma error and we will check for length and extra chords greater than zero is equal to so you looked up the mx for the domain using the net package and there's a function called lookup mx that you get in that net package and you got the mx records or optionally you must have got the error so if you got the error which means error not equal to net you'll just print out the error and if you got back the mx records then you'll check if the length of the mx records is greater than zero if obviously if it's greater than zero that means that mx that this domain has mx records so we'll set mx is equal to true has mx is equal to true okay so this has been used now comes the txt records which are your spf records okay so we'll use net dot lookup txt package so here um i just want i wanted to observe how easy these kind of things are with a language like golang if you want to do the same with uh node.js for example you will have to use an external npm right something like that um i mean i'm a node.js user i've been using it since many many years now i have uh built multiple products with node.js so um i should have nothing against node.js but actually i do so i do have a lot of cloud against node.js because to do something as simple as this you have to uh you know do a lot you have to do a lot of bending uh in case you know a better way to do this with node.js do reply in the comments and to share it with me i don't know but with golang it's super simple right you don't have to install any external package there's all these are you know the standard golang packages that you're using right now and that's insane right a language that has so much support out of the box it's just killer this is that's why you know it's the language i use the most right now uh so here also you look up the texture codes which are basically your spf records right so if uh similarly you'll check for the error so if you say you'll say if error not equal to nil then you'll do something here so you'll say log dot printf error percentage v slash and comma error and then what you'll do is you'll you'll range over these records so range by by ranging over if you're very new to golang i basically mean like using a for loop to go over all the values okay so we'll go over the text records and the right syntax for that is for and records so this is going to be your iterator and this is going to be your uh every single value that you'll have access to with the help of range records so inside your text records you'll range over them and every single value inside that text records you'll have access to it using this variable called record and here you could have used the iterator like i or j or something like that but since we don't want to use it we put a blank character here because in golang you can't just define something and then not use it okay that's why you have to use blank characters so here we'll use the strings package provided by golang again by default and you'll use the record record is basically every single value like i told you from this text records once you range over it every single value can be accessed using record so we're passing strings.hash prefix in that function we're passing uh the record and we're checking if this uh it has been represented like this so usually the spf records in your text records right all your txt records and that you want to find or search the spf one records okay if the way they represented so if you go to your let's say your godaddy or your name cheap you'll see that you'll you have these dxj records and they will look like this they'll have like a v is equal to spf one and so you'll obviously set the spf has spf is equal to true and then you'll also have your spf record which will be set equal to the record now and then you'll just break away from this program so a few minutes into the program we have already checked for the mx records and spf records all we now need to check for are the dmacc records now to check for the democracy calls we will again use the net dot look up txt but we'll check for dmarc plus the domain domain again is that same variable that was passed into this function and here we'll say dmarc records comma error so whatever is coming back from this function the function is lookup text that you have already used in the net package you're passing domain plus the dmac record to check if you know you're looking up the remark records using the same function and whatever you're getting back you're either getting an error or you're getting the dmac records so we'll check for the error so if error not equal to nil say log dot printf and we'll print out the error and otherwise we'll range over the dmacc records to do that you have to follow the same kind of a syntax and here you start to say if strings dot has prefix record comma v is equal to d mark one so you're doing you're following the same uh method process there's no change here all right same process and here instead of record spf 1 we're saying dmacc one and if it does then we'll say has the mark has become equal to 2 true and dmarc record value is equal to the record value and then you break away and at the end you'll just print out all the results right so you have to use the printf method and to print out the values so you'll say um i'll put the percentages later on percentage vs later on the values that i want to print out to the terminal our domain has mx has spf i have this reference right domain has a mix has this we have all these this was just text and here we're actually pushing out like printing out those values but in the same order spf record comma has daymark comma d mark record so how many v's do we have to put here one two three four five six so let's say percentage v comma percentage v comma percentage v comma delta v comma percentage v so it's five now and then the last one is six six percentage v and this whole function is complete now all we have to do is test this function and we know that we'll get some errors and then we have to solve those other errors and everything will work to actually find the errors and see if it's working we'll have to actually run it on our terminal so here i'll say go run main.go and as you can see it's working so i'm surprised that there are no errors it's working everything's working fine let's try entering mailchimp.com again i've tried it with many of the websites like mailchimp and sendgrid send in blue all of those main big uh email sending tools you can try more um domain here actually any domain you try you can try it here so this as you know the request will time out after a while and then we'll get those results and if it doesn't give you any results then that means there's some error with our program but i'm hoping it'll give some output yeah so we have got that output that timeout be expired and then you know you get your dot com true false true and you get the d marked records okay so i hope you enjoyed this program uh this project this is a very small simple project but you know obviously it's a nice flex you can flex in front of your friends you built like an email verifier tool all right in this video we're building a very simple aws lambda function using golang so aws lambda is a serverless technology where basically you create functions and you host them on the cloud and you only pay for usage so whenever only somebody uses your functions only then you pay for them so there are a lot of use cases for serverless it's a growing technology everybody's uh shifting their stacks and hashtags to serverless these days and uh it's a very i found it to be a very good fit for let's say if you're building an mvp because you don't know if there will be traffic coming to that product right it's not a proven product so you don't know if there's any traffic that's going to come to it so that kind of uh you know um at least ensures that you don't have to keep paying for your servers right you only pay when somebody uses your product um and a lot of people use it throughout the development life cycle like they uh throughout the product cycle life cycle right like uh right from uh the pro poc to the mvp to actually scaling because the scaling uh in serverless uh using lambdas is very easy because you actually don't have to uh write any like huge configs right you don't have to create servers everything is done automatically for you on the cloud uh so it's a completely managed fully managed service you don't have to do a lot basically right so you just have to focus on the business logic which is just creating your functions and everything else is taken care of by the cloud it's also very cheap to use because you're not paying for the servers right you're only paying when somebody uses your programs or functions so if you're building an api that's going to be you know exposed to the world and the world is going to and there are many more developers who are using your api then aws lambda is again a very good use case for that now there are a few drawbacks to using aws lambda for example uh there's cold start wherein you know if you're if somebody's using your lambda and basically the lambda takes a while to start so that's called as a cold start because there's a slight delay there sometimes uh so they've tried to reduce it but it's still there i feel uh cold start problem is still there so so drawbacks will always be there but it's a it's a very good technology everybody's kind of adopting it everybody's using it it's widely used very popular it's important right so it's important to learn and so that's why i wanted to create this video uh which is the basic uh creating a very basic co-lang function and then deploying it as a lambda function in aws now uh you will find a lot of videos where people use the gui the aws gui to deploy a lambda function but in in my case in this case i'll be using aws cli because i did not find many uh tutorials actually i didn't find any tutorial on youtube which uses aws cli to deploy uh golang lambda function all right so that's why i thought let me create one because i don't use uh the aws gui a lot i use the aws cli all right so now there are two prerequisites to this video one is that you should know the very basics of golang and actually even if you don't know the very basics of golang i'll explain line by line the whole program to you it's a very small program so that's probably not a big prerequisite the second one is important second one is that you should have aws cli installed and configured on your laptop or on your whatever desktop machine whatever that you're using right so that's that's kind of important you need to have aw cli installed because like i said you know i'll be showing you the aws cli approach not the aws gui approach because that's something that many people have covered already right aws cli i find it to be quicker faster and uh you don't have to like leave your window and if you're a nerd like me like obviously you like working on your terminal you don't want to use gui right now for uh now the next video that i'll create after this will be a complete serverless stack that will be creating right we will create apis that can be exposed to the public and those we'll create using lambda dynamodb and api gateway that's a complete serverless stack that's in the video that's coming up soon in that case since i don't want to create very complex config files i'll use the aws gui to deploy the lambda functions and to actually configure my api gateway um but only because the config files are going to be very very complex like yaml files so that's why i want to do it on the gui and not from and not write those yaml files so that's why uh here because uh it's kind of easy i'll just use my cli all right i hope that makes sense and even in the upcoming video i'll create uh config files if you want me to i'll show you how to do that but i kind of prefer going the gui route in a project that's a little more complicated all right that's just my personal preference so having said that let's get we'll have to get started now a lot of talking has happened so this is my terminal and uh you don't you don't necessarily need to um keep the project in a folder where your golang is installed right like go path and go route could be somewhere else you can have the project anywhere else doesn't matter because we'll be using the uh like like we always do right the golang 1.12 uh the the format that came after golang 1.12 which was basically uh you know using co mod in it right which can initialize your go mod file anywhere it doesn't have to be in the root or path so but uh usually also i i prefer keeping it in the go root and go path because i've been a golang developer for a very long time so that's why i prefer keeping it there but you can keep it anywhere right so because i'm i'm saying this because i get a lot of questions on youtube saying that hey my go path is you know configured like this where i'm keeping my project like this is that okay and do i need to keep my project in guru so the answer to that is you don't have to do all of that you can you know keep it anywhere i i keep my projects in the go root most of the times because that's how i've been doing it since very long time before even before golang 1.12 was there right so you don't have to do it i mean um you know the go modern it takes care of everything you don't have to do anything so let's create a new directory so we'll say lambda yt example okay and so we'll cd into it lambda yt example and here we'll just say go mod in it and to initialize i'll say github.com slash akil slash um go lambda function lambda function three okay because i've created many lambda functions on my aws account so i just need to be sure that this is a different lambda function all together all right now this is my project file project name and i don't have to keep the same name as my lambda function that i declare in my aws but i'm just for consistency's sake and that's what i'm going to do i'm going to have this name the same exact name in my aws uh lambda console as well when i declare the function all right uh so there are two parts to this video uh as in the video will be one but then i'm dividing it in two parts like contextually the first part where i'll be building the golang function with you which will be a simple function and the second part where we'll deploy that we'll we'll do the aws configuration parts the second part is slightly uh where you need to pay more attention uh because that's where all the magic happens and the first part is just creating the golang file so if you want to go quickly through the first part no problem uh you know just make sure that you slow down in the second part where i actually show you how to deploy uh the golang functions because there are a lot of caveats there a lot of different you know working parts there and uh one small mistake will completely mess up your entire deployment all right so now what we'll do is we'll open up our code editor i'm using vs code you could be using anything else and let me bring uh vs code here all right and here all i have to do is i just have to create a main.go file and we'll be just using one dependency in this entire project that is it all right so this program is going to be short and we're going to code a bit quickly in case you're new to golang main.gov file is basically the entry point into the project and in this program since it's a very small and simple program we have only one file which is the main.go file right and the way main.go file starts with is you write package main on top and you import a couple of packages here other packages that you want to use in this file and you have the most important function from uh where basically the control of this project program starts which is the funk main all right and sorry i need two packages one is called the fmt package and the other is called uh the lambda packet so i'll say aws slash aws dash lambda dash co slash lambda all right and we need that lambda package obviously because we're creating a lambda function and fmd basically helps us if you need to go lang again fmt basically helps us with some basic functions like printing and all right so golang is very modular even printing is not there in golang so you have to import a package which is a native package by the way for uh printing stuff right and all we're going to say here is we're going to say lambda dot start and that so lambda is basically this package that we have imported and start as a function that that package gives us and here we'll say lam handle lambda event which is a function that we are passing to this function all right so this means that handle lambda event is a function that we'll have to create here so we'll create that function and lambda event and it accepts some things and it returns something right so what does it accept except it accepts an event so we'll say my event and it returns a response it can also return an error if there's an error and here we'll just basically return response right now let's define what response and event are so we'll say type this my event and my response are two things that we'll define here so my event is basically a struct similarly with my response is again a struct so in case you're new to golang structs are basically your own data types that you can create which are a combination of multiple different data types all right so if i'm creating a data type called my event it's going to have name which is a string and json what is your name by the way i have more than 100 golang videos on my channel so if in case you're planning to learn golang do take a look there are a lot of different type of projects and the way i teach golang is that i basically show you how to build projects and not just teach the basics right so it has just two things name and age all right event so string which is basically what is your name and end which is how old are you and it's going to store um an integer which will be the age out here all right and your my response duct will just have message which will be a string and it will be json and answer okay in case you're wondering why we have to define json like that we're just you know defining that for the purpose of golang golang understands string and end it doesn't understand json right but what we're going to send when we invoke our lambda function we're going to send jsons to it right so that's why we have defined how it's going to look in json so here in my response you already know that my response consists of message so it will say message fmt dot sprint f is a function that helps you to format your strings and you'll say percentage s is percentage d here's old now you have to substitute percentage s and so you'll pass those values here so you'll say event dot name comma event dot h so event will have the name is let's say john and how old are you will be the age so uh all you get in the response when we invoke this lambda function is we get john which is percentage s percentage string right the name is uh 32 years old or whatever like whatever you want to send here and here for the error you would want to pass nil because it passes response and error so for the error we are saying send nil for now and this is what the entire program is about i mean that's it 24 lines even if you remove these spaces it becomes even less but i won't remove that space so it becomes like let's say 20.2 lines that's it that's all we're going to test right now right so that you basically come to know what lambda is how it works and then once you're comfortable with it then uh we'll build the entire serverless stack project all right so now is a good time to go back to our terminal and we'll start doing some operations here now i'm obviously assuming that you already have aws cli setup right and now there are three things that you want to do in the beginning itself now these three commands that i'll show you here are from the official lambda deployment documentation so if you open the lambda documentation for aws deployment documentation you'll see these things these exact same steps right so this is nothing new uh and i'll copy and paste these in the description box below as well so that you can copy and paste them and also there's and you can easily find them on the internet so you don't have to worry too much about it the first command that we're going to paste here is basically a command that creates a role name right called lambda x which will have the right role policy documents and that's what will basically allow you to access lambda on your aws account all right uh so when i press enter in my case it it should give me an error saying that this has already been set up for my uh account ideally that's what yeah so it says an error code uh it already exists right now the second thing that you need to do is you need to go back to your function here and you need to create a file called trust policy.json and this is something that lambda requires right to be able to trust the program that you've created so i'm going to copy and paste some json code here and i'll share this code with you in the description box as well so that's all you have to do now these two steps like i said are directly from the lambda documentation now there are there's another third this is the third command that you need to now put in your terminal i'm not sure why it's not coming just one second yeah so this is basically pointing uh to the trusspolicy.json document saying that this is the you know rule policy document here all right so in this case also should give me an error because i've already done it all right it's already exists and now there's another another command so there are four commands till now right so this fourth command also is very similar there's some issue with copying and pasting that i'm facing right now so all that these functions are doing are helping you to basically set up your policies and roles and permission all of those things all right so now that the basic work is done and now golang won't basically sorry aws won't stop you from uploading and deploying your lambda function now because you have already the trust policy document so all you have to do now is you have to build your main.go file so you'll say go build main dot go so it says that um i have not installed this package so i'll say go mod tidy first this is what's really great about golang because it doesn't make let you make any mistakes right so you'll say go build main.go so it's built the so as you can see this main right this is the executable file which we want to uh send to lambda now before you send or upload anything to lambda you need to have that file as a zip file so you'll say zip function.zip and you're going to zip the main project right so now if i ls they'll have this function.zip which is the name of the file right so we will call zip now it's possible that your particular ubuntu terminal doesn't have this function called zip right so if you're on ubuntu it's very easy it's i think it's just sudo apt install zip and similarly if you're on powershell or on powershell it's also easy i think you can use the choco installer now package installer and on mac you can use homebrew to install zip and that's straightforward as in it just takes your main executable file and zips in into a file called function.zip and that's the one that you want to upload now comes the most important function right so i'll paste this function here and then we'll have to change the name of the function not sure why i'm not able to copy and paste it easily some issue wait actually i just bring out my notepad because i need to make changes to that uh program right so this is the entire uh function that we want to basically um the entire command that we want to run right now and all it does is it basically creates a lambda function and it gives the function a name and what we are saying is that this is the zip file function.zip and handler is basically main inside that zip file is main executable file and the runtime that you need is golang 1.x all right and here the name of my function is actually something else so that's what i need to just verify go lambda function 3 that's the name of my function so i'll say go lambda function 3 all right so i'll just copy and paste this command here and i'll run it everything seems fine right now one more thing that i forgot to mention is that this is my particular amazon account id you need to replace this number with your account id all right otherwise this program won't work it's taking a while because it has to create that lambda function also has to upload that function.zip file so it will take a while and then the last command that we'll build we'll be running will basically be for invoking that function so in the meantime while this function is running just copy and paste that other function here that we'll use to invoke so as you can see what's happening here is it's basically this function this command will invoke your lambda function in my case the lambda function is called go lambda function 3 right and so this uh part this i found from stack overflow this is not in the documentation if you don't do this and you pass json in the payload because you have to pass json in the payload right we have to pass json in the payload because that's how our request and response will work it'll be what is your name how old are you right and sorry let me just make this full screen yeah so what is your name is jim and how old are you as 33 right that's how our function is structured in case you don't remember this is what is your name and how old are you and the answers for that is jim and 33 and whatever happens like let's say even if there's an error or the response will be formed in a file called output.txt all right and if you don't so this is something that i didn't found find in the um lambda documentation decide to find from uh stack overflow because when i was passing my json i was getting some errors so just make sure you write this little you know text here and so this is your program now if you see here if this has stopped you know this is basically deployed and everything seems to be fine and it's giving you the latest version so your lambda is deployed and now you'll just say control c and now you want to just pass the last command let's try and invoking it and seeing what happens something wrong with my copy and paste let me actually start another terminal i will see it into the directory is called uh lambda something like that right sorry yeah user cd lambda and yt example and here yeah so this is the exact project that we're in and here is where i'll just run this command you don't have to necessarily run this command here inside this project directory but i'm just doing it because of habit so again it'll take a while to invoke so it took about four five seconds to invoke i say status score 200 and execute latest version which is called as dollar latest now how do we know uh that everything worked fine because we need to check for this file called output.txt so we told our lambda that you invoke this function and whatever output that you get by sending this payload into the function you write that in a file called output.txt so that's what the file we need to look for so as you can see this there's a new file called output.txt here you click on it and you say that jim is zero years old which is wrong because it should have been 33. so that means our program is misfiring i need to just check for that now so we'll just go through our code quickly and see the issue the issue seems to be out here because there's no question mark here so when we're passing this here right as a question mark or just remove this question mark for now for now just remove this question mark because if we remove add a question mark here we'll have to redeploy this entire function by uh you know zipping it right so for now let's just change our invoking function and copying it and pasting it again here and let's see what that what happens so we'll wait for it it has uh completed the execution now it shows jim is 33 years old right so what's happening here is basically it's matching this completely properly like even if there's an extra question mark it won't read this value right so just make sure uh these both statements they match and that's the only error that i got and everything else seems to be working fine so that's it you know that's your complete lambda function and deployed to the cloud when now when somebody uses it or you use it only then you have to pay for that particular usage otherwise everything is perfectly fine in this video we are building a very basic lead management system or crm using golang and go fiber and this is a completely beginner friendly video so if you have no uh hands-on experience with golang this is the right video for you to get get your feet wet and start working with golang now i'll be using a very basic database called sqlite so it will be very difficult for you to set up or start using okay and uh i won't be using any concepts that throw beginners off with golang with like i won't be using any pointers difficult advanced struct modeling i won't be using marshalling and marshalling i won't be using like channels and go routines i wouldn't use any of the concepts that people the beginners find really difficult to understand so this is a great product to get started the only prerequisite is that you should have sql lite installed ideally if you're on ubuntu uh it's very simple it's very easy to install sqlite just one command i think uh apt get installed sqlite you don't have to do much so with that out of the way um let's let's start uh setting up the project so i'm in my terminal now and it doesn't matter how you go path is set up we are creating a new project using go mod so that will create the entire package for us and do the package management for us so we can create this folder or this project anywhere in our computer okay so i'm going to create a new directory and i'm going to call the project go fiber crm i think basic and the cd into it and i'll also go mod in it i'll just give my username and then i'll give the name of the project go fiber crm basic now go mod in it creates a go.mod file which is going to basically contain the list of all the dependencies that we use in this project so you open this up with i'm opening it up using vs code you can use any other code editor and here i'm using uh if you if you go to your golang if you go to your vs code extensions the first few extensions that come up when you type golang just install those uh because that'll just make your experience better in the sense they'll rent the errors and the issues for you by default and i've i've already done that so even if you don't do it it's completely okay but if you do it then you're just able to find those issues much faster and easier the way we structure this program is going to be really simple we just have a database folder we'll have our lead folder and we'll have our main file now main.go file is the most important file in your golang projects and this is basically the entry into your project and in your lead you'll have a lead code go file in the lead folder in your database folder you'll just have a database.profile so with main.go this is how you start the main.profile right it's called main and the second thing that you usually write are the import statements for the packages that you might want to use and then the most important function here in the main.go file is usually or it's actually always funk main so this is how you write funcman you just create these two brackets and then you create these two curly braces inside which you'll actually like the function definition and um since i've only told you that i'll be using golang fiber for fiber i'm going to go ahead and install it so i'll say github.com now um since we're using this package whenever you want you've written down any packages and you want to install them you just have to run this command called id and you'll find all the packages that have been defined but not installed yet and we'll install all these for you so i'll go ahead and find the model for package and install it automatically okay what you want to do is you want to create some routes so we'll create some routes we'll say funk setup routes here and the routes will be simple there will be uh get leads right in the crm here there will be a create lead so we'll have app dot post new lead there will be delete leads so app dot delete there will be okay and uh now you've been calling this app but what is this app exactly app is basically an instance of your file so you'll call the fiber library like this and you'll say dot new okay and you'll go to the next line you'll say set up routes and you're going to pass app into this folder i meant function part folder so into this function which is set routes you pass app which is basically an instance of your fiber and by the way you've seen that this squiggly line has gone away that means it has done it's done installing the five word package for us okay now if you're passing phi app here in this function that means you have to accept app into this function right so this is how you accept it so you say fiber dot app i know it's there's a star here and it's a pointer and i said there's no i'm not going to using any pointers but this is just one little exception okay i won't be using it anywhere else but just to give it reference and to it you know refer to the app that's being passed into this function we have to use the pointer so in case you don't know what pointers are don't worry right now i'll be creating very basic videos and explaining pointers but for now you just have to remember that app has been passed into this function and we don't uh we just want to uh use it or call it by reference just remember that call it by reference as in we don't want to directly um you know use app and uh why and how it works and what our pointers all of that i'll be explaining a different video in a very basic kind of video for now just remember that you just have to put a star here that is it right that's all you have to care about anyhow so you have uh defined these four uh these three different things but i need one more okay i need one more it's called just getting one lead dot get and just get lead so how this is working is that for this new lead you'll have a route which will help you create a new lead and for getting all leads you can have get leads for getting just one lead using an id you can have get lead function and then delete lead function is will be for deleting a particular read with the with an id okay so uh now you want to have app.listen this starts off your server at the port 3000 and and you also want to uh connect to the database uh but what i'll do is i'll just define the database first and then i'll come here and then start we'll connect with the database now you want to create a function here called init database okay and you want to go to database.go and here you want to write package database we'll import a couple of things and we'll define a variable we will define a variable to be able to connect a connection or to be able to create a connection with our database so we'll call it dbcon as a representation or reference to db database connection and it's going to be of type corn dot d now gorm is basically uh golang orm which helps golang to interact with the database otherwise you would have had to write all those queries yourself but here you don't have to because you get the help of gordon and now that also means that you'll have to import god because god is not is an external library right so you'll say github.com slash jinzu which is the name of the person who's created gorm and then right corn you'll also get the exact um support for the exact database that you're using so the database that we're using is called sqlite inside corn we have something called as dialects and you get sqlite so dialects basically means language right so uh inside gone what what language do you want to use so we want to use the sqlite support language basically to be able to connect our co-language sqlite so what you want to do is you are put a slash here and then just copy and paste it here right and just run go mod id again and you'll get these two packages and the script line will go away so always just keep running uh go more tightly right so i just run it some time back and i got all the packages so your database.go file is complete now we'll come back to our main.co file here what you want to do is the database that you just created right the database file that you just created or the database package that you just created you want to import it here so you want to say github.com slash account slash uh the name of the project the name of the project is go fiber crm basic so just write that same name here and slash database this tells golank that you want to import the database package that you just created here in this folder and you just want to import that so once you import that then you can access the code that you've written there okay so this makes the golan code monitor in the sense you don't have to keep everything in the same file you can divide it into different packages and you can install or report those different packages into your main.com file and this is how i've imported the database package that i've just created into the main file all right um now um what i want to say is in my um main file our main function how to call a function called init database and i want to start a connection so you have both we have just defined the db connection variable right so you want to say database which is your database package which we are accessing using this database dot db connection which is the variable that you just created which is of type column.dp remember so you say database or db connection dot close at the end now differ uh is a statement that you can check out it's it's a golang statement which basically means that this line that we've just said that the connection to be closed will happen at the end when the function has completely run everything has happened after that only this function this line will run this command will run which will close the connection right so we're just making sure that after everything is done after the whole funk main has executed only at the end when everything is done just at the end just before the uh you know end of the program the last pro the last line or the last command to run will be this one database connection up close anyhow so um this in a database function that you have called here and we've defined here we can now start defining it properly so first you'll define a variable called error and you'll say database dot db connection just to remind you database is our folder the package that we just created here database.gov package and dbconnection is the string that we just created so we are accessing the database package in the database connection string just like we did out here and we also have our error and here we say gone dot open sqlite3 and comma leads.tv so what's happening here is that you use gorm to open a connection to your sqlite3 database the database name specifically is leads.db and you get that connection in this database dot connection or uh if it's not connected you'll get an error now with the golang what you do is you handle error red after every single operation that's taking place so just as this has happened that are taking place we want to handle the error right here itself so let's say if error modification you want to panic and say failed to connect but if everything went well then you want to say connection open database and you'll say database dot db con dot auto migrate ampersand lead dot i'll explain to you what this is and at the end you want to save print ln database migrated okay now lead right lead that you see here you want to define the lead now uh the reason we're getting squid lines here is that fmt is not imported fmt is a package that helps you to print now golang is so modular that it doesn't even have the ability to print on its own so it's there in a package called fmp that you have to import into your program and then you have to use print println and this keeps go angry light and fast so um you also want to have um yeah i think this this looks good yeah so you want to uh now we want to talk about lead university basically lead is going to be this package here that we'll define right so firstly we can find this package we can say package lead right just like package database we defined it's going to have some import statements and most importantly it will have a struct now we won't have any uh difficult or anything these trucks and you know relationship between the structs and modeling all of that we don't have any any of that just have one struct start is basically a data type that you're creating on your own so there are some data types that you get with golang like string and hint and that's all we're using we're just using string in it in this video so you get these kind of data types with column write string and but what if you wanted to create your own data type uh with the combination of strings elements and you can do that with golang and it's called struct right so structs your own data type that you're defining out here and you're saying that lead is of the data type struct and the struct is going to have is going to be modeled it's going to have name company email sorry company email and phone so for a lead management system we'll just have name company email phone that's it phone will be inked now what i'll do is i'll just create proper spacing between them so that it all just becomes a little more readable and um that's that's about it actually so this is how what you need is going to look like right so when you go back to your main.go file you want to now import that lead right so right now obviously the lead file is not complete but eventually at some point of time will be completely complete but you would want to import the complete lead package into your main.com file because you want to run some operations on it and um so how do you import it you just do the same thing just this is your main part of the project right uh your project is github.com i killed slash go fiber basically because that's how you had defined it when you was doing a go mod in it right that's how you initialize the project and uh you can always put a slash here and you can say lead and it'll know golang will know that you're talking about this lead package out here now uh all these functions right so get leads get lead newly deleted functions we can either define them inside our main.go file or we can define that in the lead file and keep our main.co file lean and simple and small so that's what we're going to do we're going to keep all those functions in our lead.go file and we're not going to keep them here so that means that um those functions will be in a lead package and that's how you refer anything in another package in a lead package we'll have these functions get leads get new lead and delete and the way to access them will be like this the documentation dot okay now you want to define the actual route right so that will be slash we'll keep a lead right so if somebody using postman or using um you know girl hits this route api slash v1 lead then he is going to be able to get all the leads if he uses the get method if you use the post method on the same route you'll be able to post a new lead and for the um get one by id and delete by id it'll be same but at the end there'll also be that id of uh you know of the lead particularly cool this is what you get right this is how you're set up the routes now the program looks complete right and we'll head over to our lead.go file now so it's saying that i don't recognize what gom dot model is it's giving you a squiggly line that means you have to import the corn i think my video had stopped for a while i've just switched it on back again anyhow so with import uh you want to import the god right so you'll say github dot com slash gen zoo slash now you notice that it doesn't give you a squiggly line out here and that's because gold line already recognizes it because it's already there in your co dot mod right ginger.com is there so you don't have to run go more tightly again you just have you can just um keep this or import this into any um in any file once you've done go mod id once you have imported it in your project right so now you'll again get your go fiber so i'm just going to go to my main and just copy co fiber because um i'll be defining the functions to work with those dogs so that's why i need go fiber here again and similarly that what i need uh in the database the sqlite i'll just copy and paste that also here all right and i also need access to the database so what i'll do is i'll just copy this line and i'll put it here so soon in a while i'll need access to the database right the database connection all because i have to um for those get all leads and post it i'll have to work with the database so i need access to database connections that's why i've imported the database as well and now i want to define all these functions that i have in my main.com file which is basically get leads get lead new lead and delete so let's do that quickly so first function will be get leads second function will be get just lead third function will be new lead and fourth function will be delete delete now they'll have they'll accept some things and then they'll have their own uh function definition so just do that for all of these now what are they going to accept right they're going to accept c which is basically your fiber dot context fiber rcdx in case you have no idea how context works don't worry i'll have another video and the basics on explaining context but this is a very basic concept of golang and in case you know already know that's really good but if you don't know it just remember that to all these functions that are uh being driven from these apis right from the apis you hit it out and you call a particular function there you have to pass your context to your fiber okay so i'll just give you a very basic idea what this is doing is that this function now can start to work with the data that's coming from the user so for example in my get lead function in my delete function i'll need to use id right and i can use that i can find that id in my c dot params basically c will have all the data that's coming from the user so let me i'll show it to you with an example you understand it so for example in my func get lead now i want a particular id right i want to read off particular id so that means i need to define a variable called id and i can now get access to the params that the user is sending the user is going to say that from the postman or curl that hey i want the i the lead for this particular id so that id you'll have access to that id using c dot params so this is why c which is of type type fiber dot context is important so uh what we'll do is we'll just copy this and paste it everywhere make sense now um let's just finish this function off first so here i'll have a variable called db which will be of type database.connection and i'll have a variable called lead which is of type lead now i have the id that the user has sent to me that's saying that hey i want the deal of this id and i'm now going to my database to fetch the data for that particular id and what i'm saying is that db which is my database or dbconnection right which is the instance of the database session that's going on right now i will find in it the lead with the particular id so i'll say lead with the particular id is what i need and we'll say c dot json lead so we are able to also respond using c the fiber context will also respond we are able to send the response right so we are able to work on the request we are also able to send the response using c dot json and we'll send the lead in the json format okay so this kind of saves our effort from marshalling and marshalling now with the get leads we'll do the same thing we'll say db is equal to database dot daily connection and we'll define available leads which is of type lead but it's a slice now when we say get leads we are basically saying that get all the leads that exist in the database you're not saying that get a particular lead with a particular id we're saying get all the leads in the database to do that you need um something called as a slice which is almost like an added you need a slice of all the leads right so lead in this case is the struct that you've defined and when you say slice of leads that means that there can be multiple such leads with this particular struct right um or in short uh in if you're from a javascript background you would understand that it's a it's an array of objects it's not just an array it's an array of objects that's what a slice is okay so you have variable leads and you have the slice of type slice delete and you'll do the same thing you'll say db.find and you can say db.find because db is the instance of the session for database connection right so you'll say db.find and you'll get all the leads and you'll response send the response you did just see.json will say it needs to send all the leads similarly you want to also have uh the code for new lead and again you'll start with db is equal to database dot db connection and you'll define a variable called lead which is new lead and if uh is equal to c dot parser lead header or equal c dot status as the three dot send error return okay so what's happening here is you get um you use uh body parser that you get in your fiber right in your fiber package you get access to body passes it parses the body of the lead data that the user is sending to you so the user is using postman mostly postman or girl and it's sending you the data for a new lead this data needs to um you know uh checked first so we'll parse it we'll do the body parser and if there's some problem with parsing it right it's going to send an error so this error is 503 that we're sending here but if everything goes well we'll just create that lead so let's say dot create ampersand lead zero json and once you have created that lead in the database you want to send that lead just to show the user that hey this is the lead i was just created in the database right now and uh this is how you create a new instance of the lead okay so the new lead function is quite simple is just using body parser to go through the data of the lead that the user has just sent and then checking if there's an error or creating a new lead and then sending the response with that same read i hope that makes sense now delete lead to delete a lead you need a particular id right because you want to delete a particular need and so we'll say id is equal to c dot paragraphs id and you'll say database is equal to database dot table connection we will define a new lead of type lead when you when you write something like this right you say var lead lead right you've done it here also but this is um you know um i probably didn't realize that maybe it might confuse some some people right so lead is the struct that you've defined right it's the data type that you have defined which is almost like var lead could be an end could be a string or could be a lead lead is your own data type here so lead is the name of the variable whereas lead is the data type which in this case is lead itself which is a start okay now you want to say db dot first lead comma id and if lead dot name is equal to is equal to none we'll say c dot status 500 dot send no lead found with id and you'll return from here and say db dot delete never send elite and see that send delete successfully delete it so um we get the id right using the same method that we did for get lead sorry this lead here is actually capital l right so i hope you can see what the issue was there shows that there was a small l here the red written lead but it will always be capital l because that's how you've defined this lead start okay so delete lead you got the id using the same method that we did in get lead you got the id right from c dot params then you have db which is the instance of the database connection then you define a lead of type lead struct and then you find the first lead that you find with this id now if you if you uh if the name of that lead is nothing which means that lead is not there that means that no lead was found with that id but if that was found then you'll just go ahead and delete it and you'll say lead successfully deleted that's about it that's it that's your lead.go uh file and then there's only one thing we are left with okay and uh this is the thing that sometimes throws people off uh mostly people who are coming from a json background or from a javascript background is that javascript understands json by default right so whenever javascript developer goes to another programming language like golang or python or java or anything else rust ruby whatever they get confused with this idea of that how can a language not understand json right it's because json is javascript object notation and obviously only javascript understands it natively but all other languages like golang we have to massage uh the data the you know the language to be able to understand json so what you need to do out here is with name you'll have to say json name and you'll say json company so json email json phone what i have done is i have used these backticks and inside that i've used uh said json and i've used in double quotes name company email phone number like that and what's happening here is that um we're telling golang that in json this is what it's going to look like so for your reference uh hey golang for your reference you're saying that it's name with capital n company with capital c email with capital e but the json that you'll receive will be with small n small c small ds small b right this is how the the json is going to look like uh going to look like and we we're expecting uh golang to understand the json right so this is what i basically wanted to show you and when you say um you know that c dot json and in bracket leads you're basically saying to go like that hey whatever you've received from the database now you have to convert it back into json and select to the postman or the terminal whatever okay so what i'm trying to say here is that golang does not understand json and it understands one's constructs and it can only function or perform operations on that struct that it understands and then it then again has to convert something into json and then only it can send it to the response which we will understand or our front end will understand so this was basically your lead. go file and database your dot co file is complete as well and your main.go file is also complete and i'm just checking uh just to see in case there are any issues um in my main file i need uh gorm as well so what i'll do is i'll just go ahead and i'll get the gorn fiber and sqlite all these three packages i'll get into my if i already have so i'll remove that from here i just needed these two packages here in my main.co file as well okay so i think we are ready to be able to build this file now so you want to uh um before you run this file you want to build it so what you'll do is you'll head back to your tunnel and you'll say go build name as soon as you build it you see this file called just main it's just called main and what that means is it's an executable file it's a dot exe file it's executable and uh like dot exe uh if it was windows it would be dot exe file but whatever uh operating system you're using you'll create and create a uh operator like an executable file for that operating system so that you'll be able to run that program and now all you have to do is uh go run main.go and it'll run the program for you as soon as as soon as you do that you need to see these two things connected connection open database you have to see that database migrated in case you don't see any of these that means your program is not working properly and you need to check the code i'll push the code to github as well so this means that our project is working like we see this nice fiber uh you know text here and then you have your port 3000 on which it is working so everything seems to be fine you have four apis for hunters okay so now all we have to do is go to our postman and this is the collection that i've created for my go fiber basic uh project there's an add lead here as you can see right so i'll create this ad agree this lead so this had an id it has created ad updated at delta and then you have your name company email phone now these three time stamps right created updated deleted these can be added automatically uh when you add some data and these are optional right now you don't have to add them but but you may have seen that in many programs it's added automatically and i've shown how to do that using the time package in my other projects since this is beginner friendly project i have not used the time package i've not shown you how to use those timestamps okay and i'm sending it manually from the front end or from postman so here i'll just change the id i'll create another record i'll call this alex clinton let's call him alex clinton we'll call the company name microsoft and email would be alex at microsoft.com and we'll change this phone number a little bit we'll send and you can see that let's create another lead for us if i want to get all leads i'm uh you can see that i'm in the same apis that i have defined here right so if i go to my main.co file um api slash v1 lead so you come here localhost 3000 and api slash v1 that's the apa you're on you send and you can see we have created these two leads so it's working perfectly you created two leads you can see those two reads now you want to get a particular lead right so you'll come here and you will now look at the api uh which is the get api for the particular id in the end you want to add an id right so in the end i've added two i do that i get my ramsay beaters and if i add one i get my other guy and if you want to delete a particular lead it's the same right same api as in same route but the method is delete so you want to change your method here from here to delete and you want to delete the lead tool so it says lead successfully deleted and now when you check get all leads they'll show you only one lead make sense that means your entire project is working this is your simple lead magnet system this is a very simple beginner-friendly project we'll be building an hrms which is a human resource management system and we'll be using golang go fiber and mongodb so essentially you'll be learning how to use go fiber along with mongodb but um in a in a format of a small project so it's very it's a very good way for a beginner to get their feet wet and actual uh you know up applying what they've learned till now now since this video is very uh beginner friendly uh i won't even be having different files i'll be having everything in the same file may not go file so we won't be learning about project structure here because it's ugly again for complete beginners and but in case you want to see more project complex project structures and design patterns and all that i have a lot of projects already on my playlists without further delay let's get started and i'll just open up my terminal now you can see i've opened up my terminal now i'm using powershell on windows for this project and it doesn't matter how you've set up your go path or how you've installed go we'll be using go mod and that means that we can have the project anywhere and go mod will handle dependencies for us so i'll create a new directory for myself for this link project i'll call it go fiber hrms and i'll cd into it and i'll open up uh so before i open up this on on a vs code or any other code editor i'll go ahead and say go more in it which initializes your mod file and you'll give it an absolute path you'll see github.com and the name of the project go fiber hrms okay and now you can go ahead and open it up in a code window i'm using vs code vs code works out really well for golang so in case you're using something else just drive your code once so as you can see there's uh already a file called co dot mod that exists for me right and it mentions my uh name of the project and also mentions the version of golang that i'm using so that if anybody else takes up this project they can easily install all the external packages that i'll use using this file and all the external packages that we'll install in our project for example the drivers that we'll use to work with mongodb you'll see them listed out here so as i said we'll have only one file in this project and um so main.go is the file the most important file usually in the golang project and what you want to start off with is you want to say package main and you'll want to import some things here okay and after importing those things that we'll talk about in a while mostly around the things that we'll import will be mostly packages around mongodb uh we also want to create a instance instance of a session with mongodb so that we're able to interact with mongodb and it will be basically a struct so instance struct and you'll have a client and you'll have a database so a struct is basically your own data type so you get some data types with golang like int string uint you know all of those float and all of those different uh data types but what if you wanted to create your own data type right uh you can do that in golang using something called a struct almost like an object with javascript and so it will have two different things one is client one is db and uh here we'll have to write some things which i won't write as of now because we have not installed those packages but to be able to work with this struct i'll need a variable called instance now this is how you define variables in mongodb in golang you have this variable mg and subtype this is the data type so it could have been string it could have been end but right now for this uh for what we're doing right now it's instance among which longer sense is our own data type that we've just created right it's a struct it has a client it has a database okay so i also want to define two uh constants so the first constant will be the db name name of the database that i want to work with db sorry name and it's going to be called let's say we call it fiber hrms and don't define a constant for url now in this video i'm going to be using the localhost mongodb that means that mongodb is installed in my local computer and it'll be running on a port and mongodb usually uses 27017 as the native port now you could be using mongodb on your local machine like i am using to keep things simple but if you are using a fully managed service like mlab they will give you a link to embed in your program and that's the link that you put here in the mongodb uri okay so in my case i'm using localhost so this is how i'll write the link so it'll be mongodb and after these two slashes you'll put your own actual link that you got from your managed service in my case it's just localhost and my port is 27017 the way you have configured up your mongodb also makes a difference here because you might have to write your username at the rate your password and then uh your localhost so in my case the way i have configured my mongodb i have not kept any username or password for my admin user to uh as an activity with mongodb without recording any username or password uh in case uh you don't know how to set it up like that there is a video on how to install mongodb uh i think it's long i uh put it up long long back so you'll just have to search red bit on my channel and you'll find it it's very simple it's very straightforward right you just set up mongodb without any users or passwords it's just you know easier to work like that especially if you're building very simple projects right and here you want to add the db name the dv name is fiber hrms and that's what will be added so when your mongodb gets connected we'll get connected to 27017 and by default to this database called fiber hrms now comes an important part which is basically how you'll define your employee now in human resource management system means it's a company and they have a database of their employees that work there so the employee will be a struct now um you can you can manage name like name as a string or you know salary as a as a string or as a number but how do you manage all of that together for one employee right so that's why you create a struct right so there are these data types that golang understands then there are these data types that you can create called structs that you can make go like understand because they have these uh different fields like for example there'll be a field called id field sorry field called id field called name just name and field called salary field called age and all of these fields will have a data type like string for example name will be string salary is float and age is also float right so now these fields like id name salary h there are data types string or end or float whatever so that means golang can understand what we're trying to say right but all of those combined make up a struct and since golang understands those individual things like id name salvage it will also understand this whole start right which is now a new data type that we've treated for uh argues okay now uh there's there'll also be something else that i'll add here but not right now and i'll explain to you what it is but uh just keep this like this keep this as just a struct for now okay now you'll have a function for connection which basically helps you to connect your co-link to mongodb so you'll have the connect function here and every function basically takes in something and returns something so error is what's returned by this function if things go wrong and it takes in nothing basically so this so there are these empty brackets right and inside this will be a function definition that we'll write in a while and at the end will be funk main so funk main is an important function usually the main file funcman is the most important function and that's where the control of the program uh usually begins okay and um here you want to first define your app now if you've used um node.js by any chance uh and if you use express because you have to use express with most days right mostly so if you've used express that then you know that you have to define the app variable in the beginning which is basically an instance of express and that's how you interact with express and exactly that's what we're doing here because fiber is the equivalent of express so express is for with node.js and fiber is with collage it's an exact equivalent but fiber is like i think they say it's 10x faster or something like that it's really fast basically that's all i need to know okay so um now when i say fiber dot new that means i should have had the fiber package so this is how you install or sorry in the import statement this is how you import an external package so you say go fiber slash fiber slash v2 sorry it's a small v okay so small v and um you also want to get some mongodb related packages but for now let's uh let's just keep it this much and what we'll do is we'll go over to our terminal and whenever you import a new package right you have to say go mod typing so that golang will go online and find the model package for you and will install it in your program now after your fiverr definition you want to have the standard functions so which are also your routes right so the first route that you want to define is slash employee and this is the get route then you'll so this this the first route with the get method is going to help you get the list of all the employees that are there in your database then you will have a post route and then you want to have a put route and a delete route okay and for post route the route will be the same for put there will be just an id after employee for delete also there will be an id and the way you start off a function is basically when something lands on this route or some or somebody calls this route you want a function to get called and that function basically can return an error if something goes wrong and it will have a definition right the function will have a definition the function usually takes c which gives you fiber dot context you know c which basically is type of fiber which you get access to from here from the library fiber dot context now um there's something really important here for you to understand is that um whenever you have a function like this like a route function you want the request you want to be working with request and you want to have the ability to send out a response a json response by request you mean whenever the user sends let's say from his post manner from curl whatever the user sends to the program and it could be an id it could be uh like in the in case of the post request where you want to add a new employee it would be the new employee data right the data for the new employee so that will all come in the request so you need the ability to be uh to work with that request and you want to be able to process that like let's say you added a new employee or you depleted an employee using the id or you updated an employee using the id and you need the ability to also send out a response back to postman or to the terminal so uh both of this can be done using uh fiber.context and c is how you're going to be accessing the response and request okay so this is what was important for you to understand now uh before you start with all this right you also need to be able to connect with the database so you'll call the connect function here and connect function exactly the same function which you're going to define out here so um what's happening here is you'll have f error you'll handle the error here itself and error not equal to nil then your log dot fatal here so the log library helps you to log out errors and we have not imported it here so we have to import the log library right here like this all right and um what you want to do now is we want to start creating our connect function so convert your connect function and we'll say dot new client basically going to create a new client for mongodb now this word basically comes from the library that we have not installed or imported yet so let's go ahead and get the mongodb libraries the first one is go.mongodb.org driver slash so firstly just get actually just get longer right and the spelling here is uh wrong so just make sure you write the right spelling which is mongoose and driver okay so that's the main important library now this library has a few more things that you can get right the so the first thing that you can get is are the options so let's say go dot mongodb dot org slash driver slash and then you'll get some options and then has some bs on the primitive that helps you to create that id right so we'll have to import that as well so you'll say go.mongodb.org slash driver slash vsan this will help us to create the id for every single record there will be a ps1 id and we'll have again mongodb.org driver slash nissan slash primitive now if in case you're worrying that you'll have to remember these four legs you don't have to you just use it once here and every time you now connect with mongodb you just have to copy those four links i didn't copy them i could have copied them and any other tutorials will see online they will copy them but i'm just showing it to you you know so that uh you you understand that you go to go.mongodb.org website then you go to the mongodb which is the main driver which is like the main apparent library then you have like uh which is the package the orm that you use and then you have your options then you also have your psalm primitive okay so that's why i i just wrote it for you to see that they're all linked and all related so that you're not just blindly copying all of that okay but mostly from now on uh once you've done this project you just have to copy and paste these four lines every year so what happened is when i when i just uh pressed ctrl s to save it uh there are some plugins or extensions that i'm using for golang that basically recognize that i'm not using those packages right now so they have removed those packages for me so i'll control z and not save it as of now but if i try and save it it'll remove those packages that i'm not using so it basically helps with error solving and you can also go to your um what you call it your extensions and you can just write golang and the first three four packages that come just you can just install them they just make development little easier um now now that we have installed or imported these packages now it's going to be very easy for us to work with our connect function okay so you say mongod.net client and then you say options.client dot apply uri so this function right the options dot client dot apply ui you already get from the package that we're using and apply uri is a function where in that function you pass basically your uri that you've just created so all it's doing is it's going to apply that url and basically going to connect and you know create a new client for you and for that url that you've just created or just given to this program um you'll get access to this this whole thing as in the complete connection instance using the client right so whenever you want to work a client you don't want to keep writing this all the time right you want to be able to uh you want to get all of that in one variable that you can use later on so that's what the client is in this case and in case you don't know what this is this is the walrus character this basically um you know defines a variable and also declares declares and defines at the same time so here you also want to have something called as a timeout now there are some functions with mongodb that are blocking functions like insert right and you don't want it to block the entire program so you want to always have a timeout and timeout basically with this mongodb package for uh specifically uh it gives you it uses the context package that already has to give you this ability to have defined timeouts so this is how we define timeout so you say context dot with timer so in case your mongodb is not responding or something goes wrong or insert is taking too long you have a timeout you don't want to block the entire program and uh now this is not compulsory but uh this is a good practice i mean you have to it's not like without writing this the program won't work it will work without it completely fine but uh you know i recommend always writing this down okay so you'll see backgrounds comma and you can give any time here you can give a time of 10 or 20 or 30. now what you'll notice here is that um time as soon as you write time it's not recognized by golan that's because golang is so modular that golon doesn't doesn't even have the ability to print things or uh even the time package is not is even the time ability to understand time is also not inherently available inside co-language so this basically makes golang very lightweight and very fast okay that means that time um is not understood by golang that means it's a different package altogether so you'll have to come up here and you'll have to install time package on your own now uh the extensions that i'm using were able to get the context package for me automatically so when i used context out here even context is not understood by golank but somehow the extension decided to get the context package for me automatically i didn't have to do it anyhow there's a quick line here that means context there's no function called with time out and that's because uh the o should have been small and now golang starts understanding it very quickly you get a squiggly line here with client and error that's because you have defined these and you have not used these as of now and golang has a problem with that so in case you define something and you don't use it golang has a big problem so we'll quickly uh we'll use it we'll basically use these two variables okay now um you want to run this cancel script at the end of this program and that's why you use differ and now you want to say client.connect and you want to pass this context here so here um i forgot to show you that ctx and cancel are the two things that you'll get here right so when you say control c whenever you run your program right and determine you say ctrl c will basically cancel this it'll have that timeout here directly it'll just cancel the entire operation whatever is running out there so um now you have client.context cdx the context is what you will pass here to be able to connect the database with the right context and you will again get that in the error if there's an error there you'll get that in this error variable that you'll handle now and you'll also have a variable called db so we'll say client.database and you'll pass the db name here so you've connected to the database uh to the you know mongodb but you also want to go into the right database right and this is how you do it and uh you can you'll be able to use this now um the database using this db variable so this error that we have received that we may have received if things went wrong while connecting or while creating this new client those errors will handle right now so let's say if error or equipment and by the way this is a common theme with the golang that always when you write something and then you might expect an error there you will always handle that error just there itself so here we will handle the error and we'll have return errors now you might remember that we had created our uh mg here right our instance mg and here we'll say mg is equal to instance then you'll have client comma db and you'll return nil from this function okay so if you created your mg which is your instance which is a flight start and the way the values here for the client and database right have now been set so this is what we did here in case you didn't understand is that for the client it comprises of two things remember struct is basically your own data type and in this case it's longer instance which is a struct and has two things one is the client the other is the database so client means the client mongodb and database means that database name that you want to connect with and that's why we created this db and that's why we created the client these two variables here so that we're able to define our own start complete sort and mg is basically what we'll be using to you know further on if you want to work with the database so that's what your instance consists of now here you want to say that client is of type mongo.client and db is of type members make sense right now i know i said i won't use pointers and this star is basically a pointer so what you're saying is that it's a reference to dot client and mongod database if you don't understand pointers right now it's not a problem you don't have to uh you know really worry about it i'll have really basic videos coming up on what pointers are and how they work and why they're used for now here this is the only place where you'll be using it so uh and also the other place where uh we're passing a pointer to the fiber dot context so just have to remember that you have to put stars in front of these for now and we're just passing these by reference about pointers i'll create like a 20 30 minute video just explaining pointers so don't worry about this right now okay and there's no advanced pointers getting used here just just for this part so don't worry uh anyhow now coming to your uh employee start now there's something that i want to do here and i think right now is the right time to do that before we start creating all these handler functions for our routes so um one important thing that i want you to understand is that um golang does not understand json natively on its own just like if you're coming from a javascript background you might feel that you know json is always is basically understood by all languages and javascript people have uh this confusion because they feel that javascript understands co-lang json so that means all languages will understand json but it's not like that is because json is javascript object mutations only javascript understands it natively all other languages have to use some packages to be able to understand it in our case we have to use um a package called json we have to do a lot of encoding encoding and marshaling and marshalling basically for understanding and working with json and but in this case since we're using fiber fiber takes care of a lot of things for us automatically by default and it's all happening under the surface like all a lot of marshaling and marshalling is happening under the surface so fiber makes things very easy for us uh but otherwise uh by default uh golang does not understand json right so that's why we in whenever you define a struct and the struct is going to actually represent uh the data in the database in your mongodb which understands json by the way it's a javascript database and uh the data that you're getting going to get from the user as a request is also going to be json right so when data comes from the user as a request to golang it does not understand it because it's json and when data comes from the other way from the mongodb uh to golang and then golan has to send it to the user again golan does not understand it because it's coming as a json so this is why you have to tell golang that hey you understand id as string and this is what it's going to look like to you right id is going to be string and names interesting but in json it's going to look a little different so we just have to tell we just have to help uh just go like here and we have to say in json this is going to look like this man id and we'll also write omit empty for id and as you have may have worked with golang it also sorry with the mongodb it also needs pson for the id and this is how it represents id at the database level id comma format now when i i'll show you name also and then i'll explain the difference here okay so what's happening here is name is understood by postman is understood by your terminal when you uh or by the user when you send a girl request right name is understood as in json as name with small n whereas golang understands it as name with capital n and for column it's a string right but when it comes to id um the postman stands just as json id whereas mongodb stores us at as bson which is underscore id so this is why we have written bson again right for this for mongodb i hope that's understood and then you have your salary which is again json and your age which is agent json right so all of these fields they have small n small s small a whereas for golan to understand and go like to work with this information it will be capital n capital s capital a so now we want to start working with our main functions the main handler functions like get and post would delete all of these functions right and the route handlers so we'll start with get that means we want to get all the employees from our database to do that you need um like i told you golan does not understand json right and you'll get something from the database golang needs to understand it and go language to send a json response to the front end or to postman now to be able to work with that i need my a variable called employees and it's of type employee right so this is how you define a variable you say this is the variable name this is the type and you see these two brackets here that means it's a slice so it's okay if you don't know what slices slice is basically like an array but instead of containing just numbers it contains actual objects by objects you mean basically all of the things the multiple things that this area will contain will be an actual uh employee the whole employee right so this means that if you're coming from a javascript background this would mean that it's an array of multiple objects so now you initialize it using the make command and employee so um you've defined your employee variable right this will help you to work with the records that are fetched by the database from the database now to get something from the database you have to use um the find command that mongodb already has right so the find command you usually send a query in our case since we want all the employees from the database that means the query that we have to send is completely empty or just two empty brackets okay so we'll have to define the query here so query is equal to the sound dot t and inside these two curly braces you'll define the query usually in our case the query like i said are just two empty brackets because it's an empty query so this is uh the query basically so we've defined the query now you want to use the find function that mongodb will give you and inside that find you will pass query right the query that you've defined here but you'll also pass the context right so you'll pass e.context and you'll pass query here so i hope that's making sense now um this find function is available to you inside mongodb you know that already and how are we talking to mongodb in our program we're talking to it using the mongodb instance that we have defined here right the instance and the instance has something called as db so we want to uh target that instance and we want to talk to the database exact database inside that we want to talk to a collection collection is like a table so with mongodb you have collections and with an sql database like post like postgres or mysql you will have tables so if you're familiar with tables it's the same thing this is a collection so you want to go to that instance you want to go to the database and you want to go to the collection and then you want to basically uh run the find command that means you'll go to the instance mg dot you'll get the database inside mg right so it's mg and this database you've already defined the variable there already it's all be set and dot you want to get the collection so the collection so it's c capital and everything else is small collection is employees and you'll say dot find and you'll find the query and here what you get back is usually the cursor basically it'll have will have all the uh employees records or you'll get back the error so now you want to handle the error so you'll say error and for the error you want to return a status of 500 which is basically your internal server error you want to send a string which is your error string basically sending the entire error itself you've defined your employees already here okay one small mistake that i see here that i've made is that this bracket is not here it's actually here the closed bracket because it's a slice right it implies the slice this is how you find the slice there's two brackets and then employee all right now what you'll do is you'll use this cursor and here also i see one small mistake is that d is going to give you capital we will be small and now go language understand it so that's why the squiggly line quickly goes away all right so now what you want to do is you want to say cursor dot all c dot context comma ampersand employees when i say ampersand employees i'm basically passing a reference to this variable employees that i have sent and what's happening here really is basically whatever data we've received in our cursor right and from this function that you've done here cursor which is all the data of all the employees from the back end that has been received and this is going to basically convert that into a format into the structs that are understandable by coolant so that's why you pass these employees right so in in the end you'll get um employees right but that will be basically a slice of multiple different employees and we did this because gold line cannot understand json which mongodb understands and when mongodb sends some data from by running that find function you don't need to convert it into something that golang understands right and this is how you've done it so you'll say if error is equal to sorry in front of this you want to say if error and error is not equal and you want to return c dot status 500 dot send string error dot error right and here you wanna return if everything goes well you want to return the employees that you just you know now converted employees was that variable that you defined which was a slice of employee right that means multiple employees will be there and that basically is what you got from the database you converted into a nice uh you know understandable and understandable format and in json you sent it in json to as a response to the front end okay so i hope all of that makes sense now we'll move towards our post function so we'll make some space here for for post function we'll have our func and similarly this function will also accept a pointer to fiber dot ctx which gives us access to our response and request this is how we're able to talk uh use response request and it also does a little bit of marshalling and marshalling for us like here we did c dot json so it can do some mastering and marshalling for you by default it does take a lot of work away from you and gives you some abstraction so here you want to find your collection so we'll say collection is mongodb dot database dot collection and employees so instead of uh saying this again again mgb dot db dot correctional employees i've defined it and i can now use it in a variable called collection and i'll create an employee now um when creating something in a database right you have to use the insert function that mongodb will give you and also you will get just one employee that one employee data that you're getting from the postpan that as in the user will send the data of a new employee and that that new employee uh right variable is going to basically go to the database and this is how we'll define that employee variable is equal to mu so when we say this right um you can define it like this or you can say var employee and employee you can say like that or you can say implies equal to new employee all that's doing is that it's defining a variable employee which is of type employee you know the employee structure that you want to define which has id name salary image right so now you have defined your employee as well and what you'll do now is um you'll get some data in the request you'll get the data of an actual employee as in the user wants to add a new employee so you'll send a new employee data like name and all those different things uh your name and salary and age to this api and this api needs to now read that information and it does that using c which is basically your fiber context dot body parser so you'll say worry parser and when you say employee here that means all that data basically becomes formatted in the format that you need and you get it into this variable called employee right so it basically passes the body which is json you're sending from json into post from postman to this guru lang program into struct that golang now understands and after you've done that you want to handle the error so you'll say error is equal to c dot body parts are implied and if error is not equal to nil uh there can't be any space between exclamation mark and is equal to and here you return c dot status 400 dot send string error dot error okay now we always want mongodb to create its own ids and this is why what we'll do in the beginning is we'll say employee dot id equals zero this force is mongodb creates one id and now i want to take this collection that you have defined here so it's good that if i define this as a variable because i can now start keep using it i don't have to always write this again again so i'll say collection dot insert one now insert one is a function that i get with mongodb so if you're familiar with mongodb and the functions that you get mongodb it's really easy to understand you can insert one insert one basically takes data and inserts that into a database just one data into that insert one function you'll pass c dot context comma employee so you received some data in the body you used body parser to convert that into employee which is your employee struct and that employee stack basically is your is what you're sending to the insert one function along with the context and whatever i get back from this function after inserting right i'll keep that in a variable called insertion result and also an error so if the the error is there then i'll handle the error if error is not equal that is return c dot status 500 dot send string error dot error spreading the return is wrong now after it gets inserted it will come in this variable called insertion result while you'll get an error and this error will handle it right now itself and we want to do something with this insertion result what we're going to do is we want to um get the id from this insertion result that you get right then this id we'll use that to search the actual record uh that has just been inserted in the database and then after finding that record we want to return that to the front end okay and this makes us doubly sure that whatever we did the post request for right now it was inserted into the database and we can make it make that short by actually going and searching for that record using the id and then sending that record and this makes it very sure that uh this data was actually inserted in the database make sure yeah that makes sense all right so um here first i'll handle the error okay quickly so if error is not i'll give some space here then you wanna do something you wanna return c dot status 500 dot send string and error dot error all right now like i said you know we want to take the insertion result which is insertion result and we want to get we want to we want its id right so we want the inserted id and using this id we'll create a query and then we'll find the record that has this id to check if what we just inserted right now using insert one was actually inserted in the database or not okay and so let's say value is equal to insertion result inserted id and basically we're building up a query right so the key is id and for that key which is id the value is this inserted id that you just received and close it with inside another pair of curly brackets and say filter is equal to this one dot t just like you had created a query here for get which was um bs on the d and it was the query was empty right now you have vsan.d it's called sorry it's called filter not filler filter and based on these and the query has key which is id and the value of id is basically in session result that you just receive right now and the inserted id of that and you want to get the created record that you just created how do you get it you use collection dot find one and you pass c dot context to it and you pass this filter query that you just created you pass it there and that's how you get the created record so i'll repeat again you uh inserted the employee data that we just sent using postman then complete empire data and you used insert one query to insert that data of employee and you got that uh you know whatever you got back from this function was stored in insertion result and that insertion result also has a variable called inserted id which basically has the id of the data that just got inserted and you keep that um you know to to build a query and you keep that in this variable called filter and this filter is basically what you send to find one function and we're just rechecking that this data was created and then you get that into this variable called created record so this is the record that was just created right now by you and this is what you want to send to the front end so you will create a variable called created employee now want to structure and format that data right so you say that created employee is a variable of type employee which is your own struct right so created employee will have id name salary type employee and you want to do you want to say created record dot decode and you want to decode the created employee okay we are doing this decoding because as you know go line does not understand json so we have decoded that into a created empire right the whole json that we just received from mongodb and now you want to send that json as response to the front end so you'll say return c dot status 201 dot json by the way 200 201 203 400 500 these are standard uh you know statuses uh http statuses you can read more about them in case you don't know which status is used when so you'll send the graded employee make sense now um i've actually used insertion result here so let me make sure if this is the same spelling i've used here here's the scenes wearing now uh a lot of these packages have these quick lines so what i need to do obviously is i need to say so it gets all those mongodb and driver options since i have not done that for quite some time now and if i go ahead and save it it removes one package on which package it did remove any let me actually um so yeah just save it actually for now and you can see that all the issues have gone away right we don't have any issues now now we want to work on our uh put function but let me first check if everything looks fine with the post function if there's no big thing that we're missing as of now yeah everything seems to be all right so now we want to work on our put function put is basically your update and then you have at the end you have delete so i'll just create some space here just for some you know uh clarity and here as soon as somebody hits this route you want to call a function you want to call the function and this function is going to take c which is of type fiber dot cdx returns an error yeah now the thing with ids is that you get them very easily you can access them pretty easily using the c which is the context c dot params so the parents will have the parameter which is id that you just passed and i'll capture this in a variable called id param and also i will create it uh from hex so i'll say primitive the primitive package that we're using let's say object id from x id parent and i'll store that in employee id variable or we'll get an error so either it'll get converted or we'll get an error so it's giving us quickly line for primitive that means yeah so that means when i saved it last time i did remove the primitive package here so i'll copy this paste it here and i'll stay slash all right showing me three issues in the file i know there are two issues from here because these two we have defined but we have not yet used anyhow so now we'll we'll go forward we'll handle this error that we might receive here so if error is more equal to nil you want to return c dot send status 400 okay and just like you did with post right so update apis are usually very similar to the post apis so just like you defined a variable called employee and it was of type struct which is employee start similarly we'll have it here right and similarly the data you need to get from the body parser and you want to get it into this variable called employee so very similar so you will define a variable called employees of type employee and you can define a variable like like i said you know where employee employee or you can just say is equal to new implied there's two ways to define a variable in golang many more but uh these two are the most most widely used so here you'll say c dot body parser and employee just like you did in the post api and you'll handle the error here error not three are ours just two hours if error is equal to less than error or equal to nil then you'll return c dot status 400 dot send string err dot header now i'm going to start building up the query okay so because uh why do we want to build the query because uh the id that we've just received in this api right from the request for that id we need to find the exact record in the database and then with this new data that we've received to update we want to update or replace that data with this new data make sense so first we need to find the data for that id how do you do that you create a query you say based on d and you'll say key is underscore id comma value is employee id that you just defined out here okay then you'll say bsn.d and now what you want to do is you want to build the update quit how do you build the update query you uh want to have so when you do an update query right you have to have dollars set as in set this new data for instead of the old data so in case you already are familiar with mongodb will be very easy for you to understand if you're new to mongodb just remember that dollar set is the operator that you have to use inside mongodb to set this data for the data that you are replacing so this is how it's going to look like it's going to be sunday inside that you'll have a key and the key will be dollar set like i just mentioned comma there will be a value for that and the value is defined like this this one dot d inside that you have three things you have three things inside here a few things about the three fields to it one is the name comma value employee dot name and here you'll have key h comma value and employee dot h then you have k salary comma value employee dot salary makes sense here you'll just put a comma here and then here also you put a comma so now that you've built this query you to capture this and read it in this variable called update now you can see all the squiggling score went away quickly and you want to write the update function so the function update function that you get with mongodb is called find one and update so let's say find one and update you pass c dot context in you pass the query and when i say query i mean this query that i just created with the id so you find that video with the id and the update basically is the query where you set the new data for that particular id right so you pass query and you pass update both of these things you say dot err here and where you want to run this you want to run this very similar to what you've done before right you want to run this query in the instance like this the instance that you have right among instance which is mg dot database dot um collection just like you did here with your app.get right so the same thing you want to write here you want to say mg dot tv dot collection inside that collection will say employees right and error is equal to all of this now you'll handle the error so guys i just need some uh energy drink because i'm getting you know it's a long video if you don't mind all right so if error is not equal to nil that means that the filter did not match any documents so you want to say if error is equal to dot there are no documents right so there's an error and an error is that mongodb does not have those documents then you're going to return c dot send status 400. so 400 status you mean you know it's for not found that means whatever id that you're trying to find and replace the data for it does not even exist so there's something wrong so that's what you'll do otherwise if there's a regular normal error then you just want to return 500 all right and uh you want to set the employee id so inside employee dot id is equal to id param and uh if everything has gone well you want to send 200 saying everything is okay you want to send the employee so let's say return c dot status 200 dot json and employee cool now the only function that's that we're left with is uh the app.delete function but you may have realized that till now we have not actually started our server right we've not done anything to start our server so to start our server we'll just have to do just this app.listen on port 3000 and if there's an error you want to enclose this whole thing and you want to say log.fatal so if the star server does not start you do some issue like the port is already taken or there's some other issue we'll just basically be able to log out that fatal error now you want to start building the delete function the process is very similar you want to as soon as somebody hits this route or api you want to call this function which accepts c you'll have fiber dot ctx and it returns an error inside that you'll have now you obviously want access to the id right which is inside parents so it says c dot params inside that you have your id and you want to enclose this whole thing into object id from hex and let's say bring the dot so instead of doing those those two steps that we did earlier like perimeter object id from hex id param and then doing this we have done both of those things in just one step so if i did this earlier in one step you would have been confused so this is why i showed you how to do it in two steps and now how you can do it in actually just one step and you get access to employee id directly this means you don't have to do all this part with id param and then employee right you directly got access to the employee id anyhow now you can handle this error so you'll say if error is not equal to you'll return c dot send status 400. that means that probably the id that you got here is not valid so that's why we'll say it's not found 400. now uh what you want to do is you want to find the record with that id and you want to delete that record okay how do you do that you will first have to always like you've been doing till now you have to build a query because mongodb understands queries and the queries are in psalm format and this is what the query looks like it has a key and this key we're going to pass the id has a value and the value is employee id okay so it has a keyhander value and i've put a double quote here by mistake so that's why everything looks off you know it's kind of fixed and now i want to do the same thing i want to call the delete one function but where how do i get access to the defunct function i have to access the instance i'll have to access the database i'd have to access my collection the collection is called employees and inside delete one you're going to pass context comma ampersand query just make sure the spelling of context is correct and whatever you get back from this right from running this query whenever we get back you stored in result or you get back an error and you can handle the error now if error is not equal to nil then you return status um service internal server editor so let's say return c dot send status 500 and if the result is dot deleted the count is less than one so that means if it didn't get deleted then you want to return c dot send status folder for not found yeah so gonna say you wanna say that's basically not found okay uh if uh nothing got deleted or if the related count is less than one so obviously that means there was no um record like that i think uh earlier by mistake i said did i say somewhere that 400 is for not found sorry uh my bad it's actually 404 uh that's not found i got confused for 400 here's your other type of server error all right and here now if the record gets deleted so you want to say c dot status 200 dot json record deleted okay and that's your entire delete function so in about 16 8 169 lines you are able to write the entire program things look good to me and now i think we should start um testing it out and start seeing if everything works all right so what you want to do now is you want to head over to your terminal not this one sorry this one and you want to say go build main dot code now what happens is you see this main.exe file right so and since i'm using windows it creates a dot exe file for me which is an executable file and uh that's what build does it creates a build builds a exe file for you and what you want to do is you want to now run this program which is recorded let's see if it works okay so we get some uh issue here so let's try and fix things fixing it so we've received this error right and what do you make of this it says there's something to do with mango driver mongodb client right so it's quite apparent that something has gone wrong with and if i go to my code and i see that the drivers look fine to me and i know the code that i've written is quite all right and the only mistake that i see right now is with obviously is that i've not put a slash here at the end and maybe when it's trying to add this with the database name uh the whole thing is kind of fading maybe right that's my hypothesis and i save it and i run it again and i'll have to build it obviously first and then i'll run it again if you don't build it sometimes it runs the old uh executable file so just build it and now i can see that it's running the program so that was the mistake right so uh with golang you don't have to be a genius to solve errors so that's why i am very comfortable writing a lot of code and not testing it again again with other languages right you have seen other like instructors they have to keep showing you how just build a small part of the code and then they test and check check it out if it's working or not with golang you don't have to do it just write everything all at once and then easily you can debug it you don't have to be a genius we will tell you the exact issue where the issue is right anyhow so it says uh fiber is working on port 3000 there are five handlers processors is one pids to one three zero all right so now you head over to your postman and you come here i've created a collection set of collections so get all employees which is basically localhost 3000 slash employee and i get all the employees i that i have and right now it's saying that i have zero employees right it's an empty added obviously we have uh no employees that means i'll start creating employees so firstly i'll create an employee caller that's created so it's created it for me i'll create another employee called rupert uh now i see that there's another issue there's a duplicate key error issue okay so this means there's something wrong happening with our id and i kind of suspected that when i was reading it didn't send didn't show me an id that means there was something wrong there as well so now let me try and fix this id issue back in our code in the post function everything looks all right to me that means there could be some issue here yes now i see the issue there's just one small space between id and omit empty so let's remove that and now i think it'll work because this format that i had gone for it probably mongodb did not understand it so let's cancel our process buildmain.gov and runway.go and now i'll allow access on my firewall and so let's try adding some employees let's try adding robert cool you get an id here now and you add alex right so you're getting these ids here you get all employees and you'll see so many employees right now what you'll do is you want to edit an employee so let's edit rupert so i'll take this id go to edit employee just see that it's local 3000 slash employee slash the id of the employee so the id of the employees are what i want to replace and i wanna and i can send any data here that i want i'll change his name to peter when i do that rupert's name has been changed to peter so if i get all employees that second rupert has been competed but this first and third rupert are always still there but the second rupert has now become peter okay you want to delete an employee now so you just copy and paste his id again for delete employee when you paste it here send record deleted now when you get all employees you'll see that peter is not there so the first rupert is there second looper is there and peter can't be found so you can see that right the issue that we were having earlier was that id was not being generated for the first record and if i was trying to add more records i was saying that that same idea already exists so it's an error for mongodb but now the ids are being generated because i removed that small space so all the apis are working perfectly here's your little human resource management system you can create employees delete uh and updated employees you have learned how to work with go fiber which is a very nice library learn how to uh connect a program which uses go fiber with mongodb it's a complete serverless stack right so you're using dynamodb serverless you're using lambda serverless again and then we'll be using api gateway again serverless now api gateway helps us uh enables anybody across the world to interact with our lambda function right so we'll be deploying all these three things uh from the aws console right we'll be using the aws console and then we'll make settings for all these three things and we'll deploy all of this and anybody across the world can use our lambda function so this is more like a real world scenario so i'm in my terminal now and you don't really have to keep this project in your go root because since golang 1.12 anyways they had you know go mod in it which we're going to do anyways out here go modern it takes care of everything i mean you don't have to really uh do anything manually all right so here we'll say we will make a directory first we'll say go serverless and yt all right and we'll see into this go serverless stack yt for yt is basically youtube i'm making this project for youtube specifically all right and here i'll say um go mod in it and which is basically github dot com slash akil slash go serverless yt so that's my project it's initialized go mod for me go mod is basically like my package.json file if you're from a javascript background it'll have all my dependencies for me you know easily listed out so um now what i can do is i can just open this project up and code editor which is vs code in my case um just as a pointer right i'm using windows inside windows i'm i have something called as wsl inside that i'm using ubuntu 20.04 and i use multiple different versions of ubuntu right and this for this particular video i'm using ubuntu 20.04 and in my ubuntu 20.04 uh instance i have vs code set up all right now uh i don't want to install a lot of extensions uh for golang because i know when i'll start typing uh i'll start writing a lot of code i'll make some mistakes right with golang i'll make some mistakes but i will fix them so don't worry i don't have extensions because i don't want to like start uh you know ballooning up my instance because this is just one of the instances that i use uh on my windows pc for ubuntu i have like 10 15 different versions of ubuntu right so uh if you new to golang by the way main.go file is your main file right in the project and this is how you start domain.go file you say package main and you say import and because you'll import some packages right not everything you'll have inside golang golang is very modular uh you have to install a lot of external packages and a lot of uh you know packages that come with golang you have to specifically tell that you know i need this package from coolant and uh so the the third party packages that we'll be using will be mostly around lambda all right so we'll talk about them in a while and then uh the most important thing here will always be funk main because that's your entry point into the program right the funk main uh now before i start writing anything in main.go file what i'll do is i'll just try and create like a very simple project structure i need the build folder right because i'm going to keep my build of this entire project in my build folder and that's i'm going to zip it up and then i'm going to keep take that zip file to my lambda uh sorry my aws lambda console all right so that's why i need the build folder and i need my cmd folder because that's where i usually keep my main dot go sorry not in the build but in my cmd folder i use keep my main.co file all right and then you'll have a package folder so uh if you've worked with golang before this is like the very standard kind of uh structure right nothing nothing new so package will as you already know will have handlers right handlers to handle the apis and then you will have i'll have a folder for user i'll explain to you why i'm doing that and then i'll have a very simple validation function so i'll keep that in a folder called validator write daters sorry uh that's it yeah so in validators i will have just one little file of badly like five six lines of code i think it's just going to be as email valid just to check if my email is valid for the user and here in my user i'll have a file called user.go all right and my handlers that's where my main logic resides so this is a very short very small project handlers i'll just have two files i'll have api response dot go because i need this uh file for uh my api gateway i'll build it you'll understand what it is and then it's handlers.go right now my user.go file is kind of a combination of my models and my almost like my controllers as well you know so i have handlers uh but you know user.go file will have a lot of code which kind of which talks to my database all right directly talks to my database so i'll have those models like those structs as well at the same time i'll have model functions uh those uh sorry database functions at the same time i'll head over to your main.co file in funk main i think what i'll do is i'll start with this place right i'll say os dot get environment pws region so aws region is very important because that's where your uh lambda will go and sit right so with aws if if you've worked with aws a lot you know that it has different regions right so my particular aws is configured with india which is asia pacific south once uh if you have uh been using cli and it's set up it's uh it'll be amazing uh otherwise also i don't think you should have a problem right but just try and uh just try and set up awcli it's very easy it's just a five minute process and it will be very simple for you to follow along with all of my other videos as well because uh in my other videos it's a prerequisite so um how do you create a session so you'll say session dot new session now if i'm calling this os here right so i need to have os here that's the package right and if i'm calling session here session is something that aws lambda gives me aws gives me sorry so i'll say github dot com slash now i'm looking at the documentation for the aws packages at the same time you can do that otherwise in case you're you're the type of person who wants to like know uh exactly which package you are installing because i am that type of person i don't want to install any extra packages right so if you like me you you might want to open up um just like i've done you might want to open up the aws sdk it's called so i'll say aws aws sdk for go you want to you want to open up the documentation and here you'll see it will be slash session all right and to create the new session you'll see aws dot config and the bracket which will be curly braces bracket you'll say region aws dot string inside that you'll pass the region all right all right and then as you know with all everything to do with golang whenever we haven't uh we get two things usually right we get the thing that we're looking for which is the aws session which will come from the session function right sorry the new session function which is a part of the session package that we have here and we get the error so with golang you have to like keep handling errors and this is a very neat and clean way of handling errors because at every stage you know where there is coming from and you can handle it there itself so if there's an error just return all right and i want to create a variable called dynaclient which for my dynamodb and dot new and uh how do you create a new client you'll say aws session perfect which you've just created out here so you've created the session and then you'll say lambda.start and handler so this you may not understand right now not a problem so firstly we want dynamodb how do you get dynamodb you get it like this it'll say github.com aws slash aws sdk go slash service slash dynamo db all right so you have session you have dynamodb and you want aws itself in the first place so you'll say github.com slash aws sdk go slash eight plus to get this lambda function uh sorry the lambda package which has the start function you need the start function what you'll do is you'll say github dot com slash aws aws lambda go slash lambda cool so far so good that's what i needed you know and i need something called as the handler which we'll talk about in a while okay for now i am creating a constant called table name stable name is lambda user i'll say lambda in go user and now it's time to create my handler which is this basically so i'm passing my handler there in my handler what i'm doing is i have a request basically i accept some things right in this function and i turn some things and it has some definition so what does it accept except accepts events dot api gateway proxy request so you're wondering what's events right so events is basically what uh golang lambda will give us so i'll come here and i'll say github.com slash aws aws lambda go slash events perfect and the other thing that this accepts is star events dot api okay to a proxy response sorry i meant that this it accepts a request returns a response i'm not sure what i said actually before that what i'm trying to say here is that you know this is a function that accepts something and it turns something obviously accepts a request obviously returns a response right no complication there that's what you wanted to do and what you'll do here is you'll switch uh with the http method so you'll say switch we'll say request dot http method so what are the htm methods that you have you have get post put and delete that's all you have so for every single different uh hb method you want to call a different function how do you do that so you'll say switch sorry we've already switched right we've already switched uh it's like um it's 8 30 here some kind of sleepy uh i usually get sleepy at 11 pm but somehow today i'm sleepy earlier because i woke up really early i have joined this martial arts class that that you know gets me to wake up at 5 00 am these days so so you'll have something called as handlers right and where will those handlers come in from it's basically these handlers that you want to import so which are basically your own uh creation your you know the handlers are your own creations you'll say github.com handlers cool so you're saying to go lank is that uh this is my project github.com go serverless yt inside that i have a folder called package instead of a package called handlers right and handlers the file uh on top of that file will say package handlers and it belongs to the handlers folder then golang understands okay that this is what we're talking about all right that's the format i mean the the folder name and the package name have to be the same just letting you know in case you didn't know that i mean um i mean i'm pretty sure you knew that but i'm just making sure right so you have request table name and diana client right so you send this to this function called handlers.getuser which we'll work on in a while so that was your case get now you have more cases right you have depending on the http method so you have post you will have put and you'll have delete post you'll set it on handlers.create user again you'll pass request comma table name comma dyna client for put you'll pass return handlers dot update user request comma sorry request comma table name comma dinoclient and for delete we'll just do handlers dot delete user and same things you'll pass the same things comma dyna client and after delete you will just give it a default if you work with case search and case statements you obviously know there's a default right and try to keep the identitation same it won't affect it but just it's just a good habit you know i mean i don't do it many times but you know i try to do it these days all right so by default you want to call this function called unhandled method which is again in your handlers file or handlers package and this is the entire picture i mean uh i don't think we're missing anything we have the os package down here we have events lambda aws session dynamodb yeah there's one more package actually if you look at the aws sdk document then you want to import h sdk go slash service slash dynamodb slash dynamo dvi face just keep these packages and what i think we should do is we should just say go mod diary so i'll get us all the package that we've just uh talked about and usually like many times i do this at the end of the end of the video right but this time i'm just doing it beforehand itself because many people they can start freaking out hey you're you're installing all these packages if not you've not run the command go my go mod id or you're making so many mistakes man while typing why don't you install some extensions i've explained to you why i don't install extensions right so so with golang i mean what happens is that you know we usually come from javascript kind of a background and then we think that oh you know if you're making all these mistakes then the complete program will crash and uh it will be difficult to solve it but with golang golang is very different from other programming languages right make as many mistakes as you want and once you run the program golang will really handle everything for you it'll tell you which line what's the problem it's quite intelligent right it's not like your regular uh other programming languages like javascript so here one thing that we missed out was to create the dyna client in the first place right so the then a client has in the variable and defining the type of variable the dyna client is so what type of dynam uh there it will be that's where we'll use this thermodb i face right we'll say dot dynamo thermodv api just make sure you get this right all right so that's your main file your main file is complete and now you want to start handling handlers so here so since these two files belong to the same folder called handlers we want it to both to be package handlers right so we'll say package handlers right that's clear till now i'm hoping and after writing the package you say import and then you have your main func you know for in this case this the main function of this file is called api response accepts some things return some things and has a function definition what does it accept accepts status which is end and body which has an interface what does it return it returns event start api gateway proxy proxyresponse comma error right for importing you will say encoding slash json and github.com slash aws slash address lambda go slash events okay all we're doing with this is basically defining the response right so we'll say response is equal to event start api gateway response the response you're just setting the headers pretty standard because the way we're going to set up these headers are something that you've already seen so many times which is basically content type and application json so we're saying that we're returning json from our lambda function right nothing uh out of the ordinary so we'll say response dot status code is equal to status and so i will be basically your like 400 for 300 uh something like that and then you'll say string body comma json.marshall sorry so you are uh if you've been with golang you already know what's matchling and d marshalling unmarshalling sorry is golang doesn't understand json on its own so it needs the help of json marshalling which is part of this encoding slash json package and uh yeah so whenever you send some json from postman into um postman or maybe terminal wherever you send some uh json uh it basically we we want uh golang to understand it also and also the information that golang produces for it to become json uh and send it as a response that also needs uh you know help a goal i need help with both so that's why it's called mastering and muscling there are hundreds of videos about it on youtube you can check it out nothing fancy or nothing complicated you have to do that in uh you know almost all the other languages right which are not javascript which is like basically java and python all these languages you have to do something like that right because any language that's not javascript does not understand json by default because json is javascript object notation so this is your api response dot go all right that's it i mean there's nothing much going on here in this file but the other file in handler's package handlers this is where we're going to spend some time because obviously there will be a lot going on here right uh so the main functions that usually will be there will be based on our main.go file so main.go file requires get user function create user update user delete user and unlock method unhandled method sorry so these are the functions that obviously that you need to create right so you say get user and you'll say create user you will say update user and delete users func update user and delete user alright so here the last function that we want to keep here is unhandled method right so for let's say if somebody uh uses the patch method because you're handling get post put delete if somebody uses batch then we'll say that hey it's not handled right so we'll say unhandled method accept some things return some things and has a function definition all right so this is uh in general this is how your handlers file is going to be like and what we can do is we can work on our is email validated uh valid file so we'll say package validators and there's a package that you get with golang it's called regular expressions and we're just creating a simple function where we're just saying if the email is valid or not right really simple all it does is accepts an email string and returns a boolean like yeah true or false we'll take a variable called rxemail we'll use the reg expression regular expression package and if you look at the regular expression documentation like i have in front of me go to the golang official documentation and check out the regular expression package um i i highly recommend you to open it if you want because that's what i've done out here in my other screen we'll use the function called must compile and i'm going to copy and paste a regular expression string here you don't really need to understand what this does you just get it directly from the documentation but if you really want to know basically uh you're just checking if you know the numbers are between a to z a to z and zero to nine that kind of stuff right that's all it's doing and it's also checking for at symbol right that means obviously if it's an email it needs to have an ad right so those kind of things just basic email validation check is happening out there do check out the regular expression document if you want to really understand what this regular expression does all right but if you want to save time just copy and paste it like i did just did and now we want to check the length of email female if length of females less than three or length of email is more than 254 or our rx email variable dot mat string then you'll just return false right so this returns either true or false if these conditions are not met then you return false otherwise you return true that means everything is fine and email is valid right obviously if this is not uh proper it's not working properly if uh length is more length is less we'll say the email is not valid otherwise we'll say it's true you can change these numbers as you want but i've kept them to be 3 and 254. all right you can change it on your taste so uh now we'll go to our user.go file and we'll just add a very 10 000 feet level i'll just set up this file now what i want uh should happen is that from my handlers like the main control you know that will go to the main file to our uh you know to this function basically and this function is calling the get user function and create user function update user and all these functions are as you know mentioned in the handlers right and from the handlers from the handlers you'll call the functions in your user.go file and these functions will be actually the database functions that actually talk to the database right so every function that you have here except for the unhandled method because it doesn't do much uh these four crud functions that we have they have an equivalent function in your user.go file a complete like one is to one function in your user.go file that talks to the database all right so let's do that let's create those functions so firstly as you know when we start off a file we import some things and then here i also want to find some variables some errors that i want to define so the functions that i want to have here in my user.google file which will have one is to one relationship with these four functions the first function will be called i'll call it fetch user so that means is uh my get user function gets called in my handlers and this function will call in my user.go file the fetch user function which directly gets uh the user from the database itself the database in this case being dynamodb right so it accepts some things returns some things and it has a function definition simple the second function that i want to have is for getting multiple users actually so i'll say funk fetch users similarly it'll look very similar then i want to have a create function so i'll have create user and then it has update user okay you just have to keep looking here and then creating these functions and then you have the last one is delete user right so you'll come here right if it doesn't get deleted then you don't have to return anything specific so especially you can just return an error that's why from the return here is just an error right and that's about it so we have one into one functions all of these but one extra function is there which is fetch users all right so we'll see where to get where to use it so from a 10 000 feet perspective this is your user.google file and this is your handlers file so what we'll do is we'll start working on our handlers function and then at the same time we'll start working on our uh user.go functions and here you'll obviously import some things right um the first thing that i need is net slash http then i need my lambda event so i'll say github.com aws lambda go slash events now it's possible that i'm importing these but you're not understanding why i'm importing these so you might get confused so uh now there are two ways to do it one is when i'm actually writing the code and then i use this events packet somewhere and then i come and come up and you know import it or i know um you know which ones i need so i'll just import them right in the beginning itself so that i can use them later on so i'm just doing this so try not to get confused because we'll actually be using these packages in just like two three minutes don't worry you know why we're importing them where will we use it so please be patient slash aws right so these are the same packages that we already use in our main.co file and we'll say github.com slash aws slashing plus okay go slash service slash turnover db slash dynamo tv i face great one thing that i need here because i would want to call these functions like i told you right i won't call these functions so that's why i want to import this user package in my handlers file how would i do that i would say github dot com slash a kill slash go serverless writing slash package slash user so inside package inside the user package we've imported it here all right and then before i get started these functions i want to define a very a variable called error method not allowed is equal to method not allowed and why do i need to create this because firstly we'll be working on this function unhandled method right so that's why we want to call this function so here this returns an event api gateway event so it will say api gateway proxy response comma error right so we'll just send response from here or we'll just send an error and here you'll say return api response the response that you want to send is http dot when we say http we are talking about the http package net http package all right status method not allowed comma header method not load which we have just defined together right that's what you're saying so we're saying that uh we have uh you know something for get post but complete but we don't have something for patch so patch or any other method that somebody uh plans to use so if you get something like that like an unhandled handle method so you'll send a response saying that hey this method is not allowed all right and i want to create another variable but it's actually a struct right so it's an error body and i'll be using it a lot so just bear with me as to why i'm creating it this struct has a variable called error message chat string error comma commit empty cool now for your get user you have you accept something and you turn something here for a get user what do you accept what do you what does the function get you get a request right from postman the request that you get is um part of this events packet so you'll say event start api gateway request comma table name which is string comma diana client dot dynamo db api and what is return it returns a response obviously so we'll say events dot api gateway proxy proxyresponse comma error straightforward and actually this these two things right well it's going to accept what's going to return it's going to be used by all of the functions so what you'll do is you just copy and you'll just paste it here for create user for update user as well and for delete user as well awesome so we've done a lot of heavy lifting now we want to start working on the function definitions for these all these functions right so the first thing that you'll say is email request dot query string parameters email so if you've guessed what's happening here is you want to get the user but by using the email id of that user so from a request you'll have your query string parameters which we'll pass as email and that we're going to capture in a variable called email and then we'll check the length so we'll say if length of email is greater than zero then you'll get a single user so you'll say user dot fetch user which we've just created together right we've not created the definition but you know which function i'm talking about it's in my user uh package which have been imported here already so fetch user is going to take the email table name and die in a client and i'm going to capture this in the result or they're going there's going to be an error and if there's an error i'll handle the error so i'll say f error not equal to nil return api response http dot status bad request comma error body so error body is a struct that i've already defined and in error body i want to pass aws dot string error dot error and otherwise you'll see hdb dot everything is okay so we'll say status okay if everything goes well and you'll pass the result from this function now if um if you want multiple users you'll say user dot fetch users same thing table name and a client and what you'll do is you'll again use result and error to capture the values coming from this function and if there's an error and you'll check if error is not equal to nil you'll return the api response saying http.statuspad request because there's an error right and you'll send the error body just like we did earlier error body is the struct that we've already defined that's the error body that we are sending which is basically json and here the error body uh inside that we're going to send you're going to send aws.string header dot error got it but if everything went well and there was no error then we're going to return api response and http dot status okay comma result so basically that's your get user now what you can do is we can work on our fetch user and fetch users both of these functions in our user.go file or we can work on our create user function in our handlers so i think i'll do the former i'll work on fetch users and i'll work on fetch user let me just check if everything is recording yes everything is recording perfectly and i just i need to keep making sure otherwise you know i end up making a long video when nothing has recorded and that leads to a big problem all right so before i do anything with users i want to first create a user right so like i said this file is a mix of that model file that you usually create where you define the struct of how the user is going to look like so i'll say user struct email now since this user struct is small and we don't have multiple structs like if this was a um e-commerce for example then you would have had users and orders and you know all those different like products and so many different structs right so you'd have to have like a model separate models folder for all these different models and then you'll have you'd have you know database functions separately and controllers or something like that right but since we don't have that we have a very small project which just has users and users all itself it's a very small struct because you just have email first name and last name you don't have too much here right you can combine controllers and models into the same file now email is going to be a string which is going to say json and you say like this json email because for golang's purposes it'll be emailed with a capital e whereas when json where it's stored uh it's going to be emailed with a small e so you need to tell golang that you know there are two versions of it one the json version the another here's the version that golang understands because golang does not understand json as i've already told you so that's why we'll also you have to use some marshalling and unmarshalling uh to get it to understand and interact with json all right so you'll have first name and last name and then what we'll do is we'll create our fetch user function what does it accept so if you actually go to handlers you'll see the fetch user function accepts email table name dynaclient so we'll say here email and table name which is string and your dyna client which is of type you already know that more dbi face dot dynamodb api and it just returns a user obviously i mean you fetch user you return that particular user or you turn error if nothing works out you define a variable called input and it's of type dynamodb dot get item input so we'll have to define the key based on which our database function will run to find that particular user and you already know that the user will be found from the database based on the email id so we take an email id we're taking an email id and then we want to find the user that's associated with that email id all right so straightforward we'll say dynamodb dot attribute value and we're going to say email because we want to run a query on email so email is equal to s is equal to aws.string dot sorry inside that bracket will pass email now the string is a function that is given to us by aws package aws packet is something that we'll have to import out here all right uh and similarly with the dyno db so we'll have to also import the dynamodb package so come here on your import and uh firstly called encoding json because like i told you golang does not instant json by default so you need uh encoding slash json package to uh use the marshalling and unmarshalling functions and i need the errors package also then i want to uh get my hands on the events and i'll be using it soon to send responses and the usual ones uh as you can see i need dynamdb and i need aws so let's get those ones so i'll say aws slash aws sdk go slash aws and i'll say github.com aws slash aws sdk go slash dynamo tv um and what i'll also do i'll also get this particular package um yeah let me do that for now so i'll say github.com aws slash aws hd case go slash service slash dynamo db slash dynamodb i face all right now coming here you've already passed this and after this bracket you need to specify the table name in which this function is going to run so we'll use the uw string function again to pass the table name and after this bracket you want to use your dyna client to finally start getting the item input is this basically the query that you created right and get item is the function that you get in a client and you will capture that in result and error so standard practice if there's an error we'll have to return the error so we'll return nil for the value and we'll return errors dot new error failed to fetch record so um you must be wondering where is where does this error come from you've probably never seen this error right because this is a new error that i've created on my own how can i create my own errors i can create my own errors like this so error fail to fetch record is equal to fail to fetch record and similarly i can define any errors that i want in this variable uh defined as a variable right so you've uh you know created a query very similar to mongodb write you've created a query based on the email because you want to search for that email so that you can retrieve the user and you've run the function get in get item for dynamodb and you've passed the query to it and you've received that in something called as result or you received an error so if there's an error you handle the error but if the result is fine and nothing really happened then you would do something right but before that we'll create a variable called item and it'll be basically a new user and here you'll say error is equal to dynamo db attribute dot on marshall map okay so dynamodb attribute is another uh by the way if you have not opened up the dyno db uh and aws sdk go documentation do that because i have it open on my other screen you can do that as well and then everything will make a lot more sense because these are actual packages inside that main package right so i'm using those and once you go through the documentation you'll understand where to use uh which one or you or if you really don't care about that you can just keep following along with what i'm doing but i just recommend that you just read it because you know everything will make more sense here i need this package right then would be attribute this is helping me unmarshalling the user so first let me write the whole code so i'll say result sorry not here here upper bracket will say result dot item comma item and this error if this error is not equal to nil what we want to do we want to return nil comma errors dot new error failed 2 on marshall record so you must be wondering what's happening here right so when you get the data from your dynamodb using the get item function into result you want to unmarshal that into an actual user which the front end can understand as a json basically so you use the user struct and you uh you know take that in a variable called item right so item is basically um a variable of type user and then uh you know you want the data that's coming from your result dot item you want that to be unmarshaled and brought into item so that now whatever has come as uh json uh becomes uh you know the type which is user which is understood by golang but and it's captured in a variable called item right um so i've tried to explain to you every single line in case you don't understand it do check out what's marshalling and unmarshalling all right and if you have any error like if you still have any confusions you can just put it in the comments below i'll sort it out for you but it's nothing very difficult right you're just um taking what's coming from dynamodb the json and you're unmargining it to uh make it into a struct right which is of type user which has email first name last name something that can be understood by golang and you're capturing that in a variable called item which is obviously of type user right that's stuck that we have defined this is standard practice i do this in all my other videos as well in case you're new to this channel i have hundreds of videos on golang you can check all of them out like literally hundreds of videos on go like right check them out build projects with me and you'll understand very everything very easily so if everything went well if there was an error obviously you sent nil and you sent the errors but if everything went well you would return the item and then you will return nil for the error now you'd want to also work on the fetch users function the plural fetch users function how do you do that you are passing table name there as you can see here you're passing table name and nano client so table name has been passed which is obviously your type string you passed denmark dyna client which is of type you already know dynamo dpi face dot dynamodb api and you return multiple users how do you run multiple users you return basically a slice of users wherein users is the struct that you've defined right so you're using a struct you're making a slice of all those users and then that's what you're returning i hope that makes sense if you don't know basics of like of course like slices and structs then i highly recommend you check out the basic tutorials before uh you get more confused so um i want to use a function but that dynamic db gives me it's called scan input to get access to table name which is aws dot string and table name that we are already passing here got it and you will say dynaclient dot scan and you want to scan the input the query that you just created right so here as you saw uh we had a more elaborate query because we had to get a particular user with email but with fetch users you're just getting all the users you don't have a specific query that okay you know for this email i get a particular user saying get me all the users so you don't have any query as such you're just passing the table name so that's when your dynaclient.scan you just pass the input that's it and scan is like get all you know you can say that so if you've used uh that mongodb it's you have find find all something like that here you just have scan find and find one you have in mongodb so you just have scan all right scan and get item so you're doing scan to get all the results and you're going to capture that in a variable called result and then you'll obviously if you have an error you know that standard way to handle errors is like this you'll say return nail for the value and you'll return an error so you'll say errors dot new error failed to fetch record and again like we did out here item we'll define an item right the item here is not just a user it's a slice of users multiple users because we're getting all the users from our database and again the same thing that we've just done here we'll do the same thing here so we'll say error is equal to just copy the whole thing actually copy and paste but there's only one small little change instead of result.item you'll have result dot items because obviously from your database you'll get multiple items multiple users that's what you're getting and you're returning your item and for the error you're turning nil makes sense so we've done quite a bit right we've already done the get user function and get user function had fetch user and fetch users two functions from your user.com file now there are three functions left here and three functions left here because we've already taken care of the unhandled method function you don't have to do anything more here so just three functions left here three functions left here and all the other files are kind of complete right so if you've reached this far congratulate yourself because you've come you've come a long way right um so now let's start thinking about how our create user function is going to work all right so for the create user function let's let's start building that there's actually not much happening there all these functions right uh create user update user delegator they're all going to look very very similar so i'm going to say user because you know uh you want to call the create user function the user package so you'll see user dot create user which is this function that's what you're calling right and you're passing it three things request table name and a client make sense now whatever response this function returns you want to capture that in a variable called error sorry result and you'll get an error which will be captured in error and you know the process from here if there's an error which means error not equal to nil you'll return api response http dot status bad request comma error body and what will be in the other body everybody in this case by the way is sorry the struct that we've already defined right so what's there in the everybody it's aws.string with a single r sorry string err dot error and comma okay and you'll return api response http dot status created comma result so if that means if there is no error everything goes well then you'll say hdb.status created all right and that's about it that's it actually that's your create user function there's nothing more to it all right and then for your update user function very similar you'll obviously call the user just like you did here user dot create user here you'll call user dot update user method so you'll see update user and you'll pass three things request table name and dyna client and you'll capture that in result comma error and then you'll check again if error is not equal to nil you'll return an api response http dot again status bad request comma error body inside the other body again the same thing it resource string error dot error all right but if everything went well if the user did get updated then you'll return api response and you'll say http dot status okay that everything went well and you'll return the result so that means what's happening in these two functions create user update user is that these two functions are being called that means a lot of the logic the main logic is going to happen in these two functions right because not much happened in the in the handlers similarly let's work on our delete user function here you'll say user dot read user you'll say request comma table name comma diana client here also though the only thing you'll run from here is the error right if the user didn't get deleted you'll return the error you don't need to return the result any result from the delete function so if the result is not equal to nil you'll return api response it you know by now what we're going to say we're going to say status bad request and we're going to also send the error body which will have aws.string and the error itself but if everything went well you would want to return the response with status ok and ultra nil for the error okay so that's um that's about it and um yeah that's it i think the entire file is complete now we don't have anything else to do i've also gone through the aws uh sdk documentation i don't think anything else need to be done in the handler so everything looks all right to me uh and now we'll have to work on our uh user.go file and all these different functions that exist on our user.com file for your create user function what all it's going to accept depends on what you're sending from here which is requestable and nanoclient so here you'll say request event start api gateway proxy request comma table name which will be string and data client which will be you already know then mdbi face dot nano db api so what is it going to return it's going to return the user that has been just created or an error so here the first thing that we'll do is we'll create a variable u which is of type user user being the struct that we will define that means you will have email first name and last name all right so let's start from there now we'll use u why did we create this variable u it's because we want to capture what's coming from postman so from postman or from let's say the terminal wherever we'll send the json of the user with the email first name and last name and that data needs to be unmarshaled into you so that golang is able to understand it and also perform any operations on it so what you want to do is we want to use the json encoding json package to call the unmarshall function and what you want to do is you want to pass the request dot body to it comma ampersand u if error is not equal to nil and also here we'll fold the right syntax for the if statement and if error is not equivalent then we'll return nil and we'll return something for the errors we'll say error invalid user data but we don't have this error here right so we don't have uh this error error fail to and marshall record we don't have error in values of data we just have error field to fetch record that's all we have defined so now let's define all the other errors let me define all the other errors that i'll need in this entire file in the beginning itself so we'll say error failed to unmarshal record is equal to fail to unmarshal record an error run and i'll add error and valid user data is equal to invalid user data invalid email also will be there and valid email is equal to invalid email then we'll have good not marshall item and could not delete item so then we'll have could not put item so we'll say error could not dynamo put item is equal to code not dynamo put item and user already exists user does not exist user.user does not exist so why do i need all these errors obviously by now you would have understood i'll just give you an example that uh when creating a user right if we check if that user already exists then we don't need to create that user so that's why we need this kind of an error and if you want if you're updating a user then or deleting a user we can use this that user does not exist so why are you trying to update that user right that's why um i'm just thinking about all the type of error functions i'll need error statements i'll need so depending on that i've just created them so coming back to your create user right here now we will start validating uh the email so we'll say validators dot validators is the package that we have created together right this one and the function that we created in that package was is email valid and you is the variable that you defined and now after unmarshaling the request that you uh in the body body is of the request that you got from let's say postman or from the terminal as json you captured that in you so now you can now golang can easily understand you because it's unmarked right it's not json anymore so you can access u.e mail and you can run the validation function on it so here the spelling is wrong so it should have been is email valid and you'll return nil errors dot new error invalid email right and now the reason why i created this uh error is because i want to see if that user already exists right so if that user already exists then you don't need to create it so we need to throw an error so we'll check if the user already exists right so i won't put that comment actually i was just trying to show you so to check if the user actually exists you have to run the fetch user function you will say u dot email comma table name comma diana client and you'll capture whatever comes from this function in current user and we won't handle the error so i'll put a blank there so if current user is not equal that means there is this user exists right if current user is not equal to nil and length of current user dot email is not equal to zero then you return nil comma errors dot new error user already exists and so all of this if the user exists but if the user doesn't exist you will just save that user right so how do you save that so first to save that obviously uh whatever you now have in you you want to start um you want to start marshalling it right so that dynamodb can understand it now so you'll say dynamodb attribute dot marshall map you and you'll capture this in av and you'll check for the error so if there's an error we'll return nil and errors dot new error could not marshall item which we've already defined we've already defined this error right and now you want to start creating your um data that you will be sending to dynamodb so how would you do that you'll say dynamodb dot put item input item is av comma table name is aws dot string table name and finally you'll say dynaclient dot port item and you'll send this input that you've defined here so yes missed the is equal to sign by mistake similar to fetch users right you created this input and then you call the dyna client function similarly you're doing that the same thing here you're calling the put item function and you'll capture that in a blank character blank variable or and or you'll get an editor from here and if error is there then you'll just handle it very easily you'll say return l comma headers dot new error could not time output item right you've created this error already but if everything went well you just want to return the user awesome so this is your create user function and now you're left with update user and delete user everything else you have taken care of right the handlers.go file is complete api response is complete as as email validate is complete and main.go is complete and i think for our user file we have uh imported all the packages except for validators so you need validators so you'll say github.com the validators package that you've already created we talk i'm talking about that one so we'll say go serverless yt slash pkg slash validators let me also check what else am i missing for handlers i think i've already imported user and i don't need any more packages for api response um i don't need more packages for is email valid i don't need anything else my main.go file probably i might have missed something so it has handlers it has os events lambda aws session dynamodb dynamic dbi face so everything is proper based on the aws sdk go right check out this documentation you'll know why i'm importing these packages and how i've used these functions you already know that because you've been building it with me all right um then we'll come here again back to our user.com file and let's start working on the update user function so what does it accept accepts request which is of type events dot api gateway request comma table name which is string comma dyna client which is of type dynamodb i face dot dynamodb api returns a user the updated user and or i mean i mean r it sends back an error and we're going to do a lot of things which are going to be very similar to the create user function which is basically we create the user first we create the user right which is the variable u which is of type user and we're going to unmarshall just like we did uh we're going to unmarshall the request body that you get so request dot body comma ampersand you so by mistake um yeah so i have to close the bracket here because this is together and this is this variable u okay and here are not equal to nil if you don't want to follow along you can just copy and paste this part right i'm not copying and pasting because uh this syntax might be new to many people because it's dynamite kind of working with dynamodb so i'm uh writing everything by hand but if you want to copy and paste if you're very comfortable with dynamodb go ahead and do that you don't need to you know practice along with me then you want to fetch the user and see if that user even exists so you'll say u.e mail comma table name comma then a client and you want to capture that in current user and you want to check for that current user so if current user not equal to nil this is exactly what you did in the create function as well and length of current user dot email is equal to equal to zero then you'll return nil comma errors dot new error user does not exist so for the create user function we were checking uh for the user associated with that email because we wanted to see you know if that user only exists we don't want to add that user but for update we're doing the reverse we're checking for that user because only that user exists we can update the data for that user makes sense and exactly the same things we'll do because now we want to start so now that the user uh you know um if the user doesn't exist we'll throw an error but if the user exists then you want to start updating the table with the new data how do you do that whatever you've unmarshaled right now from json to you know unmarshalled to something that golang understands now you want to start marshaling it to something that animaldb understands so you already know what you want to use you want to use the marshall map function i want to pass you to it because you've just unmarshaled and which package is a part of so it's part of the dynamodb attribute package we'll capture it in a variable called av or we'll get an error and now we can easily handle the error so we'll if error not equal to nil return l comma errors dot new error could not martial item this one really really straightforward now you just want to create your input item and then you want to just call the dyna client function only two steps remaining so you'll say input is equal to ampersand dyna modb dot put item input and the item is equal to av comma the table name will be equal to aws dot string table name and the last thing is you'll use dyna client dot put item and you'll pass the input and if error not equal to nil nil comma errors dot new error could not dynam output item return ampersand u comma nil so now even my update function is complete everything looks okay and all i want to do now is um run the gomot id command to get all of the packages that are you know not there so i think it's taking a while i can't find my phone anyways so um while that's happening in the background we can start working on the delete user function so as you can see it's all installed i had a couple of issues actually um as you can see and most of the issues were because i had a couple of spelling mistakes here instead of sdk i did an skd you know so a small small few mistakes i had made just make sure you get these right um you can easily get them on aws sdk go um you know documentation or if i put mostly i'll put this code on github so you can just pick it up from there all right make sense just pick it up from there instead of typing it all yourself because i made a couple of mistakes so it was taking a while but now it's installed all these packages so in your user.go file everything works perfectly right like we don't know if it works perfectly but everything looks perfect to me and all the packages are in place all you need to do now is work on your read user function which is actually the most actually the like the easiest function so it takes request event start api gateway request comma table name which is of type string done a client which is a type already know you already know that dot dynamic api all right so what do you want to put in the function definition you want the email of the user right so request dot query string parameters and the parameters email then you'll create your input to the function which is of type dynamodb and dot delete item input item input star dynamodb dot attribute value basically you're passing the email and then finding the user and deleting that user with it associated to that particular email right nothing complicated so you'll say aws dot string and you pass email to that after this you'll say table name here ws dot string pass the table name and now that you have your input ready just like we've done all other functions you take the dyna client you call the dynamodb function which is delete item in this case and you pass the input to it input basically has your query for deletion which is the email id and you get the error and if there is an error you'll return errors dot new error could not delete item perfect otherwise you just return nil nothing basically that means that the user has been deleted now i'm sure there are a lot of errors because i'm not using any type checking extension or any golang extension right so there will be a lot of errors here so i need to start solving them one by one before i deploy it to the cloud so to find those issues and to fix them i'll head over to my terminal and i'll head over to the cmd folder and i'll say go build main.go and starts giving me errors right so it says on this file line number eight um yeah i can see the issue it has to be double right that's what makes it the or operator so you'll run the command again and now you'll get all these nice errors that we were expecting right and now you want to go start solving them one by one so starting from line 37 all the way to line 145 too many errors so when it says too many errors that means that even after you solve these it'll give you uh many more errors right so this is why i don't really you know use extensions because because golang takes care of everything it tells you which exact line which part what you're missing you don't like it's a no-brainer right you don't have to apply a lot of brains just solve these issues just like woodland wants you to and everything will run so that's why i'm so chilled out all the time man so if i can go back to your code on line 37 what could be the issue it's that i have not put comma here and comma here basic syntax issues right that's what it says it says basic index issues here also you need to put a comma and let's keep putting commas wherever you know i think um it will uh need commas so this needs comma here which is line 58 in my case you can check it out where you know it is for you for create user again i'll just put a comma here just to be sure and i'll put a comma in the input part which is this all right and in the update user function again let's go to the input area here i've put the commas so i don't see any issues here and for delete definitely you need to put a comma here as well as here as well as here so now if we run it a lot of the errors have gone away right and now you have some other errors there are some syntax errors also like four syntax errors and one this one also that you're not able to refer to this function so let's try and fix those as well at the same time so let's hover over back to our code let me see the line first line says 88 line 88 blah blah blah blah blah yes m is small whereas m should be large what was i thinking am i stupid you know that i was not able to that i didn't make the m uh you know large because obviously the function is martial map with the capital m right so this just means that no matter how stupid you are golang takes care of everything right so you don't need to be the smartest guy on the planet so let's look at other stupid mistakes one zero eight comma missing it's a syntax error super simple right it's even telling you expecting comma right i mean how obvious can error statements be and then people you know tell me download this extension i don't have downloaded any extension man golang does everything for me and uh missing statement after label 125 125 missing statement after label blah blah blah blah blah yeah obviously the is equal to sign is off and then 147 147 put a comma here auto after 147 and then unexpected yep found it now let's run it now let's see some more errors yes so it found us some more errors and now you have to go to line number 66 76 and 140 but these are not syntax errors so here you'll have to think a little bit as to why there's an error there so head over back to your code on line 66. line 66 yeah so it says let's look at the error it says cannot use results dot disorder items and something something something to do with this function called unmarshall map that is because you're receiving items not item you're receiving multiple items right so you can't use that marshall map function here you'll just re use unmarshall list of maps super simple man super simple 76 line 76 all right it says blah blah blah blah blah request our body see it says request dot body undefined and it also says does not have body with capital b right i mean you don't you can be the stupidest person on the planet and fix this issue because you just had to make this b capital right so that's how intuitive go language and then you go to line number 140 line number 140 i mean i can guarantee you that you can't do any like something like this with any other language right it says there's a problem with this function obviously because there's a spelling mistake here parameters so everything is fixed now and now let's see so it gives me another error that says unmarked list of map is wrong yeah because i made a mistake again it should have been unmarshalled list of maps not map awesome so now now that your user.go file is sorted as in it first shows you the syntax errors you've solved them then you solve the logical errors and now it's giving you some issues with the handlers file right handler.com it's giving you all these syntax errors we'll solve them then we'll give you some logical errors we'll solve them as well and then we're good to go all right so we're on the right path and now let's go back to our code so open up your code and start from line 19 line 19. put a comma here line 42 42 per comma here it's because saying it's exactly expecting a comma from you right and line 54 put a comma line 59 blah blah blah blah blah blah comma line 66 and 72 96 for a comma 72 for a comma all right now you start getting the real errors right the real errors so um line 22 we just solved this issue on the other file line 22 because the spelling of parameters is wrong and now you want to worry about line nine line nine so one thing to notice is that it's line 9 but of another file api response would go so open up the api smaller go file and here i can see there's an issue all right i have fixed the issue it was basically to do with uh those brackets and now it's starting to show me issues with main.go file which is what i want i want to fix the main.go file issues but on line 44 line 44 let me see what's happening okay yeah i can see it i can see the issue it's basically all the cases have to be together and by mistake i'd written this outside the bracket also the switch bracket and i've included inside so that error should also go away and now when i do this it's created the go build may not go file for me so let me see if it has yeah i can see the main file i just have to move it here to my build folder and i've created the build file without any issues no errors right so now let's start uh the deployment process before you do anything else you need to first create a zip file so you'll just come here you'll say zip minus jrm build slash main.zip from build slash main so build is your folder main is the build that you've created for in your folder and build slash main.zip will be the zip file using the zip function maybe in your linux you don't have zip you'll have to install it using sudoku apt-get zip so now if we check here we can see the main.js file in my build folder and now we're ready to kind of start uploading it on lambda or aws lambda but as remember as you remember i told you that i have windows installed on that i'm running the wsl on that i'm running this ubuntu and on top of that i've built this folder right so i need to be able to access this main.zip file from my uh windows from my windows to be able to install like upload it on my hero player school and lambda aws lambda dashboard so for that i'll do something so to in order to help me to do that i have to run this command explorer.exe dot and now hopefully it should open yeah it has it has opened up the explorer at this location for me and i'll copy this i'll put this on my desktop awesome and now i can start to deploy this on my aws console so you want to start deploying but there's one thing i wanted to change is this table name so i'll keep this table name same as my other name of my program go serverless yt okay just for consistency's sake because we will have to create this table in dynamodb and let me just search uh if i was using the other table name sorry i'll just ctrl z and i'll just see if i was using this table name anywhere else in any other file oh it's this only place there's only one place i was using it so here's the table name has to be changed you will say go serverless righty okay and now is when we start deploying so log into your console and head over to lambda you have to just create function go serverless right so we're using golang one point x i think we'll have to change the uh execution rules create new role from aws policy templates this option is what you have to select and the role name go serverless righty executor from the templates you have to choose simple microservice permissions create function successfully created right now you want to change the handler so as you know our main uh the file that we'll be uploading is called the main file that's what our build is called right so we'll have to change the handler to main upload the zip file and upload it go back to aws and go to dynamodb and you will click on create table table name so table name is what you selected here go server syt simple right because we have kept everything with the same name so and primary key so it says enter the partition key name i think this is the primary key yeah it's the primary key so the primary key in our case is email which is string obviously and everything else is same and we can just create the database active it's now active so now you can proceed to the next stage which is configuring your api gateway so head over to your api gateway create api you want to build a rest api protocol is test select new api here and now you want to put the api name which is go serverless yd and you then create the api from the actions select create method select any and here you'll select integration type lambda function and check this use lambda proxy integration and give the name of the lambda function here which is go serverless yt and you have to also have to ensure this is checked default timeout now we need to deploy our api so from actions deploy api select new stage stage name is staging and deploy so this is your url that you get here which you will be using right now to test so let's test it out i'm expecting some errors to be there but not a problem let's clear our screen and um first we'll have to build this command so just give me a second so here are my four commands and obviously uh this is post which is creating a user this is get all users get a particular user by email id and this last command is for update now we can use postman or you can you just use curl which is the same thing right and you set your header and you tell it what's the request which is post and the data that you need to send which is email which is my email address my name my last name and this is the the unique link that i just got this link is the unique link that i just got from my invoke url okay so i'll post these comma i i'll post this command somewhere how do i post it now okay so i'll what i'll do is i'll upload this project on github and then in the description i think i'll just post these commands so that you know you can just copy and paste them directly uh i think that'll be the best option or you can just use postman i mean you have to use these commands if you don't want to all right and similarly for uh the update you say it's request put you give the new data is going to find email based on that because emails are primary key as you already know and this is my api link these are the four commands i need one more command which is the delete command so i'll change that to this so you'll get all these in the um an api gateway documentation on how to call these apis you can get that also and so i'm just copying those and i'm just changing uh those commands all right so what we'll do now is we'll try and test it i'm pretty sure there'll be some error it'll fail but let's do it anyway oh so it worked it worked all right so it created this user which is amazing let's run the second command sorry this command and now it's not copying and pasting it now we're running the get all users command so we'll get all the users so only one user is there so it's getting that and then we'll get the particular user the particular user has this email id it will get that user also for me because there's only one user right now yeah so that's also working and now we will work on our put function so it's taking my email address and changing my first name to la la la and last time to blah blah blah blah blah right so it's done that so even update is working and now we have to work on the delete function so if the delete function works it won't return anything so we'll check if that user is still there so we're getting all the users so that means delete work because it's an empty array right the same user is not there anymore perfect so that means everything is working i hope you enjoyed uh this tutorial uh it's a it's a long video i know there's a lot to follow there's a lot to learn there and i hope you really enjoyed it i hope you learned a lot in this uh project and um very soon i'll have i'll have one more project coming up with serverless stack but it's a little more advanced we'll have multiple lambda functions we'll have cloud formation we'll have you know those cloud formation scripts so and everything will be through uh you know yaml files and then aws cli and we'll also use aws sam for the entire setup so that's going to be really complicated um so make sure you've done the aws lambda uh you know that video and you have done this serverless video and then you read up a little bit more about how serverless works and all the aw technologies and that will really help you in the next upcoming video that'll be slightly longer actually much longer and they'll have like way more complicated project right so the point of that is where this is like a monolith serverless project right that will be serverless microservices project there will be api gateway cloud formation uh there will be a lot more technologies i will use aws sam for all the writing all the configuration files anyhow so i hope you're enjoying it and do subscribe to this channel if you haven't already and there are hundreds of videos on golang on my channel check them out and i also keep sharing some nice advice on uh you know your development career so you keep watching that as well all right so see you uh and connect with me on linkedin there's the linkedin uh link in my description box below thank you in this video we're doing something very interesting we're building an intelligent chatbot so till now we've built many slack bots but most of them have had a hard coded command and response but in this case we're building an nlp aware completely intelligent slack bot so we'll be using four different technologies one is obviously golang because we'll be writing the code in golang then we have slack to interact with the bot then we have vit dot ai to understand nlp responses and wolfram to actually run the computational models and can get the responses from the internet okay so vid is a technology that facebook has developed it's very similar to dialogflow by google or lex by amazon and you can basically train it to understand different um sentences so for example if i want to find out who the president of india is uh so you can have uh different type of queries right you can ask him uh you can ask the what who is the president of india or who is the president of india now or who's currently who's the current president of india so all of these things right all of these statements they uh they basically mean the same thing that who's the president of india right now right but then uh slack doesn't understand it golang doesn't understand it so vet is the intelligent nlp part where vic can be trained with all these hundreds of different statements to understand that you're basically trying to say the same thing so it so it basically uh creates like a confidence score to uh tell you that okay i've understood the query now and uh you know i understand your question so what is that nlp intelligence engine right and then once you have once it has understood the query you can send it to wolfram world fam is the competition and so wolfram has the answer of who the actual president of india is it doesn't have that answer wolfram has that answer so so vit basically can be trained with hundreds of different sentences to actually understand uh what your query means and then it will send the query uh to wolfram and then we'll get the answer and then uh you know we'll get the answer to slack so let me take you through the entire diagram of how we're going to do it so the user will enter a message it goes to slack and slack then sends the message to us go lank server golang server then sends it to vit whit then sends it again to golang server and from there we can again send to vol from because there's no connection between width and volt ram and slack and width right so our golang server is going to be the connection between all of these things from wolf wolf ram we want to send the response to slack so it has to go through our golang servers right everything i'm sure makes sense now and there are going to be some packages that we'll have to use to interact with it to interact with cool uh wolfram to interact with slack so slacker is my favorite package if you've done my other previous slack bot tutorials i'm sure you know that there are many on my channel so you can go ahead and do those as well so slacker is the package that i often use so you can look at this somali slash lacquer right on it go on github so i've kept these tabs open because all of these uh are important to us so that's why i've kept all of these tabs open right i'll take you through all of these one by one so slacker is the um wrapper on top of the slack go package uh which is a wrapper on top of the slack bear uh api right right so this is like a third level abstraction of uh how we can build a slack bot and this makes our job very very easy so that's why i always use slacker so now that i've shown you this i can cancel it out i can you know close that tab then we'll be using uh with our commands that we get from slacker the user that he enters the command it we process it and are using our slacker and then uh we send it to witco right uh using vidgo vs into vid and that's how of it will process it so with go you can think of it as a wrapper uh around wits apis written in golang so you can use this as functions you all you have to just call these functions that are written in with go all right and now uh with gives us some response that we need to we need to send to wolfram right but the response that vid gives us has uh it's a really big uh json and to process that json it's uh it's quite challenging in the sense that uh if if you know how to work with json with golang you know that it's not very straightforward you have to use struct sometimes you have to use unmarshalling and all that so uh i found this package called gjson so first let me close fit go so i found this packet called g json it helps you query json very very easily so for example and now this guy is a genius obviously so i have to give him that so ted wall or actually there are so many more contributors in him so these guys are geniuses because they have built a package that helps you take a json like this and then just access them like you would in something like javascript right which is so simple so you if you wanted to get name uh so inside this entire json object is this uh key value pair called name which is an object itself so you can if you wanted name and last you could just say name dot last right and you could get access to anderson and if you have worked with golang you know how difficult it is to actually restructure a json object like this and then get an actual access to something like this right so uh so this library makes it very easy and i'm going to use this in this video and also in the future videos i'm trying to use this a lot more uh so that that will save us a lot of time right building all these structs and then unmargining and marshalling it and then trying to access this value and it's a lot of work so we'll use this ge json right so now that i've shown this to you i'll just close it off and uh to work with wolfram now wolfram is a big uh technology right it has a lot of apis it's quite complicated so there is somebody who has written a go wolfram uh package for us now this looks simple but as you can see there's so many structs right all these different stocks are there that help you to work with that help you to basically translate or unmarshal the data coming from the apis and then it's a big file it's just one file but it's a big file right so somebody has done it for us they're calling the wolfram uh api and then getting all the data for us all right so all we have to do is just call the functions inside the go over from package like so right so you can create a client you can get query results simple and straightforward so we'll be using google form like i said and we'll just close that off right now and the other thing that we need to use uh you know uh so you know that the way i manage uh environment so i don't uh so i since i make very beginner friendly videos i don't try and confuse you with uh you know trying to set your environment so i just use os dot set environment and os dot get environment that's i do something very very simple and straight forward but this is the right way of uh setting that environment so i'm uh if you might also know that i'm also a ruby developer i've been a ruby developer for many many years and ever since golang you know i started using golang i stopped using ruby uh many years back so uh so this is a go uh you know implementation of very famous and rupees.nbc very popular ruby gem right dot and here you call them libraries but in ruby you call them gems so this is very very popular and this lets you manage uh and your environment variables very easily right so all we'll have to do is we'll have to create a dot and file and we'll put all of our uh you know keys there and then we'll be able to just uh load it simply with go dot invert load and then we can easily use them with os.get and environment variables right so this also means that i won't be pushing my environment file into github so you need to create your own environment file with your your own apis api keys so pay attention when i show you how to get your api keys uh because that can be confusing to some people right so this is the golang sorry the wolfram uh portal uh now one one uh thing that i have to tell you about wolfram uh website is it's very slow uh it can be a frustrating experience to work with it because the website somehow is stuck in the 19 uh sorry the early 2000s it's not it's not a new website it doesn't work like a modern website would and the api is also kind of shaky so obviously the the wolfram go package makes it easy for us but uh but i'm just telling you because if you can see this it's still lowering since yesterday actually so don't get frustrated just try to you know be patient and also it gives you only 2 000 requests per month so and it you can make only 20 apps uh at one go otherwise you'll have to upgrade so just make sure you stay within those limits if you don't want to uh pay a lot of money to upgrade all right and i have created these two projects here so if you want to create a new project you can just go ahead and say get an app id and before that obviously you have to sign in to you have to create an account in wolfram alpha you have to sign up and then you have to head over to developer.wolfram.alpha.com and uh as you noticed i clicked get an app id a long time back and sometimes you have to refresh it and sometimes very weirdly it would have logged me out but no not today it has not logged me out now so anyhow so i'll just click it again so now it's asking me for my application name so i'll say uh new nlp all right so i'll send you an lp what this is the youtube demo bot if you don't give a description it won't let you create a new app so i'll say create an app so it has given me this app id but but i won't be using this app id i'll be using my old app id the the one that i had created yesterday which is the nlp what uh sorry the wit ai one which has uh already has 13 total queries the reason for this is very simple uh with wolfram uh if you have not uh if you've not waited for 24 hours uh it won't let you use uh as in it gives you a lot of error sometimes and unpredictable type of error so it says uh you know invalid app id or some some editor like that so i looked it up on stack overflow and the answer that i found was that you have to wait 24 hours sometimes or at least 12 hours for the api to work correctly so uh if you create an api right now api right now chances are you won't be able to run this program properly and we'll say error app id invalid or something like that okay so that's the thing with wolfram alpha i know there are a lot of quirks with this so basically just remember to get your uh app id from here and that's all that's all you need to do at wolfram also website all right so just copy and paste it with yourself and then let's come to vid ai so here you'll have to log in using facebook because it's a technology built by facebook so we'll say continue with facebook it takes a while so i have all these bots built up and now we'll create another app called new app and let's call it then i already have a new llp so i'll just say with ai i'll just call it youtube demo all right so remember to keep it open and we'll say create and language is english and now it has a couple of things on on the left side right so you have your intense entities so we'll go to intense we'll create an intent and we'll call it uh let's see if there's a wolf ram intent already so there's no old friend intent so we'll just call it wolf ram and next right so we have this uh intent now we'll have to create entities so we'll create an entity and we'll find a built-in entity so we'll look for wolfram so the integration between wit ai and wolfram is so deep that they actually have an entity called wolfram search query so vdi would come to know that this is a wolfram search query and needs to send it to wolfram so it'll give us a relevant format so we'll say next and now we have our entity setup and this role is added by vitiai themselves and now whatever uh you send it to uh with ai right these will show up in your utterances so we won't actually write utterances and train our vti right now this is that's not the scope of this video you can find thousands of videos that train your vti or your dialog flow bot right we won't be training it we will be sending it very straightforward questions that will just identify as uh a wolfram uh query and send it forward so for example if i said what uh sorry who is the president of india right so with 92 confidence it is understood uh this question right so we don't have to train it right now that means so um but if you wanted to train it for this sim same query with multiple different uh statements you could do that right so anyways we won't be doing this like i said we won't be training it we're just sending it straight queries which are directly sent to wolfram so now that i've shown you the go dot end package i'll just delete that i'll just close that tab as well and i've shown you this video uh which doesn't work anymore so we'll close it so we won't be using any of the packages that have been used in this video we're completely rebuilding everything from scratch so we'll close this as well and we just need to keep our uh you know these videos tabs open just in case you need your uh app id so yeah i'm not showing you how to get your app id and video right so all you have to do i think um i don't remember correctly you go to settings and you will take your server access token this is the one that you want to take all right so just copy and paste that copy and keep it for now at least then let's go to our slack so slack i'll have to go to dot com api.slack.com apps and here uh if you have done my previous uh slack bot tutorials which there are plenty of you have built all these bots with me and today we are building another bot from scratch and we'll call it the youtube demo app all right and i'll select all tech as my space so it's called youtube demo and you have to switch on the socket mode so that it can catch up messages in real time so we'll say enable and we'll call it the socket token generate and you need to save this somewhere and keep it and but i'll come back for all of these api keys uh you know but you can keep them somewhere safe if you want and then we'll go to our event subscriptions we'll have to switch these on and we'll have to give it some events to subscribe to so we'll say app mention because we'll mention our bot and then we'll say message.im so these are the events that the bot will subscribe to so that it comes to know when something is happening so like let's let's say somebody mentions the bot and sends it a message it will come to know right so i'll just say message.groups as well and i will say messenger npm i am and i think that is about it i don't need to add any more uh events so always the trick with the slack is add more events than you think you'll need and add more oauth permissions so we'll come here and we'll add some oauth permissions so for now i'll just save these chinese changes exchange is saved let's go to oauth permissions and here we have to add some more scope so these scopes were added based on the events that we subscribe to but we have to add more scopes right so again with scopes the trick is to take more scopes from your from oauth of slack than you need so for example i need uh this one here called channels read and chat right because i wanted to be able to write to a channel right and i will say i am read and i am right instant message i am basically stands for instant message and i'll say mpm i am an npm read and write as well i might not need most of these permissions but i'm just going to keep them anyways like i said you know you uh they're so if you've seen one of my like my previous videos of slack you know that a lot of uh errors happen because you don't have enough permissions and slack the problem with slack is it won't even give you errors uh the right errors right so you'll keep struggling with the error for a long time and you won't know what happened because you won't get the right error so and most of them are to do with uh permissions in the sense your bot just won't work and you won't come no why it's not working so i think i have all the permissions that i needed and that is about it for me and i'm going to install it to my workspace and asks me if i can give it these permissions i said allow so now it's given me a bot user token so this is important and in our basic information the slack the socket token educated and that's that's important right so it's called the youtube demo just remember that so we'll have to uh refer it right we'll have to mention it in our slack channel so if we go to our slack channel and i say youtube demo so uh it's his youtube demo is not in this channel yet so do i want to add it i'll say yes add channel so add youtube demo to this channel only then we'll be able to interact with it right now what we'll do is we'll actually start creating that project so i'm not sure if you can yeah i think you can see my power shell so even if you're on windows or uh which is which is i am i'm in windows and i'm using powershell even if you're on ubuntu and using terminal or mac using terminal the commands will be exactly the same so what i'll do is i'll say mkdir and youtube demo nlp all right so i'll just go inside that and here i'll say go mod in it and github.com and it'll be what so uh the mod file is initiated like this so if you're from a javascript background this is very similar to npm in it so it creates a mod file which contains all the package that we'll be using in this project and this is the direct the absolute link that we'll use to access other files in our project so i'm not sure why the enter is not working on this maybe something to do with my internet yeah so it has created a mod file let me just check now what we have to do is we have to start getting our packages that we need the external packages that we'll be using in our project so you can give these in commas or you don't if you even if you don't give them it's not a problem so you'll say github.com slash uh if you're from a javascript background this is exactly the same as npm install and this is the name of the package and this is the github link for it so like you have uh the npm library the npm website nbmjs.com where all these packages decide uh golang doesn't have something like that so you have to get everything from github.com right and what we'll also do is we'll get go get github.com slash dot env and when you also get go get github.com slash uh the the slacker slack bot uh library that we need and we need the g json the one that allows us to query json with golang json sorry you have to write go get in front of it and then the last one we need is vidco the one created by alex so we have all the packages in place and all we have to do is open up our vs code and start writing the project right and here obviously the file that you'll create is main.go on top you'll write package main you'll write import and import all the packages that you need and here you'll have to write the main function so we'll say funk main and the funk main will have quite a bit of a code and at the same time we will have our dot and b file in the dot envy file you'll have four things one is slack bot token then you have your slack app token then you have your bit ai token and your wolfram app id right so volfam app id have shown you how to get it right from where to copy it i already have it copied in some place in my laptop so i'm just going to come and paste it here with ai token i've already shown you where to get it from copy and paste it here and then we have our slack bot and slack app token for the slack bot token you'll get that in your oauth and permissions you'll get your slack bot token and in your basic information you'll get your slack app token here in socket token that we created the one that starts with xapp is your slack app token the one that starts with xp is your slack bot token all right so now that that's clear i'm going to copy and paste my uh sorry i forgot to copy my tokens so i'll just copy this i'll say copy and this is my slack app token and slack what token i have to go back to oauth and permissions and copy it so our environment file is ready now we will have to import some packages that i know we'll use when we will use context and coding slash json we'll use fmp to print out stuff and json to you know work with json log and os for our environment variables and as of now i need slash shoho slash go dot environment right we we need uh other packages as well with for working with slack and wolfram and width but i'll introduce them one by one so in our funk main the first thing that we write is go dot environment and here we'll use the load function to load the environment file okay then we'll create a bot so we'll say bot is equal to so here we have to create a new client for our slack bot and that can only be done if you have the slacker package so we'll say github.com okay so let's create our bot the bot basically will have slacker dot new client os dot get environment and slack bot token comma os dot get environment slack app token so these are the two things required for our bot so let me see if the brackets have been properly closed so we have we have an extra packet here by mistake to remove that and there's one more extra bracket here by mistake so we have to remove that as well so all the squiggly lines have gone away and uh there's a squig line here with bot it's saying it's declared but not used but we'll use it soon so you do not worry about that and then there are squiggly lines with all these packages you will be using all these packages soon so you don't have to worry about them as well okay now uh since we are in the process of creating these different variables i think it's uh a good time to create our with ai client and our wolfram client as well or maybe i'll do that after a while anyways so one thing that i have to do is i have to create a function called print command events if you followed my other slack tutorials as well slack slack bot tutorials then you know that this function is simply to print out the events that the bot uh subscribes to so whenever we put a give a command to a bot uh it acts as an event and it uh publishes to the command line we want it to be open to the command line so that we come to know what's happening so we'll create this function now so this function will be created above funk main and as you know we'll call it print command events so in one of the previous videos i've already explained uh the inner dynamics of this function basically your passing command event here and we'll save for event we'll just range over this analytics channel and we'll print the timestamp of the command the command itself the parameters that it received and the event name so let's say fmt dot println we'll say command events and fmd dot println again event dot timestamp fmt dot print ln again say event dot command fmg dot brilliant render and event dot parameters like i said and the event itself and just an empty line so our print command events function is ready now i had a couple of packages here and when i pressed save since i'm using this uh golang plugin it removes all the packages that i'm not using the code right so by mistake don't press ctrl s because it will remove all the packages that we had uh you know written here but it's not a problem so what this uh golang plugin does also does is that when i use a package here it also adds it here on top so it's a two-way street anyhow so we have written our command for printing the uh the events the command events and now we'll start working on our uh pod.com function which basically handles the command that we'll send to the bot but before that we just have to write in some code that will help us stop the program and we wanted to so we'll say context dot with cancel again this is standard code that we've written in all of our previous uh slack bots right slackbot codes so in case you're new to this channel there are hundreds of i won't say hundreds with here at least tens of uh slackbot tutorials do check take a look to check them out is equal to bot dot listen ctx and if there is an error that means error not equal to nil we will say log dot fatal and we log out the error all right so like i said this is standard code and i'm using the log package here and now it's installed the package for me it's imported that right earlier it was giving this quick line here so we have uh the outlines of our function ready and now comes the main part which you need to pay a lot more focus to attention to sorry it's the bot.command function which basically helps us to uh you know understand the commands that we give to the slackbot and then work with that so we'll say bot dot command and here we'll uh you know put the command that we'll send to the plot and here we'll say slacker dot command definition and inside command definition is where all the magic will happen all right so this function obviously the command function is part of the slacker library and this is the syntax the requirements of the function itself and it has uh a description so we'll say let's say send any question to wolfgram and has an example again like i said you know this is coming all coming from the slacker library it's not something that we are building up uh all these are requirements of the slacker library so this is an example right example question these are uh both are static variables these are just the description and the example of how the spot will be used right these are not dynamic so we'll say handler handler is our function that helps us to work with the bot or with the different uh you know commands and when i pressed enter it it filled in all these things for me automatically so in case you're not using a golang plugin and it's not filled in these for you just make sure you get this right otherwise this code will also be on github and you can easily pick it up from there so we'll say query which is a variable and we'll say request so handler functions if you've seen my rest api videos of golang you know that you have requested response objects right so request is what the user is sending to this function to our golang program and in the request you will have parameters if you've ever worked with rest apis you know what parameters are so the parameter that you're looking for let's say it's called a message right and here that means we have to uh give a query something like that so we'll say query for bot right put a dash here and to pass a param in a function uh to to slack when you pass a param you have to pass it like this so we'll say message and so what you're telling to go language is that in the request there'll be param called message so when we send a command to our slack bot it'll be like query for bot and then we'll put a dash and we'll put the actual uh statement and the statement itself will be captured inside query and then this query is going to be sent to uh you know wherever like uh wit ai and wolfram now there is a there seems to be an issue here i think we have to put a comma that's what the vs code is telling me so i've put a comma here and the squiggly lines have gone away so everything looks good and query there's a squiggly line here because it says it's declared but not used right now what we'll do is we'll come here we'll say client dot parse now client is going to be our with ai client which we have not we've not created till now so i think before i create my client what i'll do is i'll show you what the query looks like in the uh command line so i'll say fmd dot print line and i'll say query so when we send this uh query to the bot it's just going to print it out and then let's also keep a response here and the response will be very simple just be received all right now reply gives us a squiggly line because r has to be capital and now everything works except for this i don't know i could not import this package i think we'll have to just run go more tidy and reinstall it back again so i'll just go to my terminal and i'll say go mod diary even i have if i had installed the package i don't know why it wasn't recognized here so anyhow uh this is what uh the code looks like as of now and there seem to be no errors so what we'll do now is we'll start this program so we'll say go run main.go and let's see what happens okay now we'll head over to our slack and to our youtube demo app we'll say query for bot and we'll say what is the capital of india so all we need to know is that yes it was able to get the message so message now is what is the gavel of india so it's able to read it it's also able to print it out right so everything works as expected and this means we can now start writing the code so now we'll create our with ai client to do that you need to create a variable called client out here so let's say client and the walrus operator and then we'll save it ai we don't have ati in our project so let's get fit ai in our project so we'll save it ai and the package will be github.com slash weight ai slash wait go slash v2 now we had installed this package but there's a possibility that uh golang wasn't able to get it it's okay we'll again run go mod id no problem so coming back here we'll save it ai dot new client we'll say os dot get environment and with ai token now again the reason that why golang is not able to get this for us is because because there's some issue with my go path obviously and since this is my windows laptop i won't try to fix it i use my linux laptop most of the times so just bear with me when i run go mod in it uh don't worry it'll install it back again for us so here we have our client with ai and it uses the vti token in our environment file all right so so far so good now it's giving us a sweet line here because we have not used our client package and that's what we'll be using here so we'll say client.parse and inside parts we'll write with ai ampersand with ai sorry in small what's wrong with my caps wait a i dot message request and side message request you will have to send a query and the query will be what you get from here from uh your slack bot so let me show you the diagram again all right you the user sends a message it goes to slack slack gives it to golang server and now we have to send it to it right so slack has given it to golang which is query and query has to be passed to vdi so i hope everything makes sense now and here we're going to print this out so we'll come here and we'll take these values in a variable called message comma blank and we'll print out the message here so now we'll run that program again and i'll show you why i've done this uh i'm not sure why it's telling me to get this package when i need the v2 and if i say command s and i run go more tidy i'll just stop this program for now i'll say go mod tidy and it has got the v2 for us right so everything works now no errors here so we'll run the program again oh yes sorry sorry sorry sorry i'll run the program again i'll say go go run main.go and here we'll say at youtube demo query for pot what is the capital of india and it's able to get the message and now this is the reply that's coming from vta this needs to be structured i'm sure you agree with me that this needs to be structured because this is not something that world ram will be able to understand so we'll stop this program here and i'll just open up the vs code editor again so the message that's now in msg we have to do something about it right so we'll say we'll create a variable called data we'll put a dash here and the walrus operator and we'll say json dot marshall indent basically want to convert that whatever response that you saw you want to convert that into json so this adds the right spaces and everything so about four spaces is the right one two three four all right and uh this will add those uh if you've seen json objects you'll you'll see that all of the key value pairs they're covered in these type of inverted commas right so that's what the double inverted comma sorry so that's what the indent function does so json is giving a squiggly line here so if i put ctrl s that should give me the encoding.json package yes so i get that so there's only one error left which is data which is basically saying that i'm not using data and i'll create another variable called rough and i'll say convert whatever data i get into string format and we're going to print out basically this rough variable now let's see what happens we'll run the program again and here we'll say at youtube demo uh query for bot what is the capital of india it does says it'll say received and here we can see that we get a nice json object that now we can work with and uh the thing that you need access to is basically inside entities inside this wolf ram search query and inside that array inside that object inside the array and inside value that's what you need the reference to right and this value this is the thing that we need to send to wolfram now there is also a confidence score which is of 92 percent so uh 92 divided by 100 is 0.92 so so it gives us a range between zero and one so anything above 80 percent or even 70 is good and we could have you know taken our program further and we could have uh checked the confidence score and then uh given the query to wolfram but it's not a problem since we have not trained our bot to understand these queries as of now we won't uh and and our vita ai is directly going to forward these queries to voltram we don't have to worry about the confidence score right now okay so you'll stop this program now and it does give a little error a problem time to you know stop it and here you'll come back here again and uh now like you know you need access to this thing right inside entities inside this inside the area inside the object inside value now to get access to this ngo line is very difficult it's not like javascript you just you know start accessing this uh working with this object directly because golang does not have native support for json because json is javascript object notation so only javascript has native access to it so what we'll do is we'll create a variable called value because we need that value right inside entities and we'll use our package the json package and with the json package you can just run these get queries to get whatever you want so we're going to run the get get query on this variable called ref and we want to say entities so i want access to my entities and i want access to this width dollar wolf ram search query and uh you know colon wolfram search query right so let me write that here with dollar wolf ram search query colon wolf ram search query okay so just check if the spelling of wolfram is okay looks good and now we want to access the first value of this array right this is an array so we have access to this now we want access to this first value of the array so we do that in an array do that by dot zero right because that's the first value so with this package with the help of this package you can easily access the values inside an array so you'll see dot zero and dot value so let me show it to you again so dot zero which is this object and inside that is dot value and you'll have access to what is the capital of india it's just as simple as that now what we'll do is we'll actually print out this value so that you'll see exactly what i'm talking about and now we'll go here again we'll start the program again okay so it's telling me to get this package so let me go back here okay again i'll run go mod id and we'll run the program again okay and here we should say again the same query query for pot what is the capital of india here you can see we got the value the exact string that we want to send to our wolfram we have it here we were able to access it using our uh gjson package makes sense so uh with the help of uh this bot right we'll be able to send it send these kind of questions like who's the president of u.s who's the president of india who's the president of the u.s what is the capital of india who's the governor of china it'll give us the exact right answers uh because wolfram has the ability to process that kind of information give the right answers so let's see how it does that now create another variable called answer and this basically converts the value that i just received here into string okay because string is what we have to send to our voltron client now that means we'll have to create our world front grant right so we'll come here we'll say wolf ram client is equal to ampersand wolfram dot client inside that here in this case there will be these quickly brackets and we'll say app id os dot get environment and we'll say wolf ram app id all right so it doesn't our golang program doesn't have access to this so let's fix that so it's added that already actually good and then it's giving me error here okay i think i'll have to create a wolfram uh client actually a variable call voltron client so this i have to make sure the cs capital c has to be capital here and here i'll have to create a constant wolf ram plant and wolf ram dot client all right and the wolfram client comes from here everything looks good right now there seems to be an error here i don't know why missing constant value syntax sorry it has to be a variable actually or a constant so it's a variable and here so it has an error here it has an error here in this place and it has an error here because we are declaring it but not using it so now i'll come here to answer actually before that let me just stop this program and go more tight again so that we get the word from package and now the errors mostly have gone away except for these two errors right the word from clients so this the volume 10 we have to use right now so i have the answer here in a which is basically string in the value in string format and i'll say world ram client dot get spoken answer query now there's uh there's a confusion here that many people have is that uh the person who's created this library it should have said get spoken on security but it says get spoken in t there's a small t here so just make sure you write that t otherwise you will face a lot of problems so here we'll pass the answer comma the answer that we get here and wolfram dot metric comma 1000 all right and we'll assign this to two different things one is the response and one is an error and if there's an error which means if error not equal to nil we will print out there is an error and the response we will send our response object rds right and to me everything looks okay and there seems to be no error as of now but only when we run the program we'll come to know so yeah everything looks good and what we'll now do is uh let me check if there's any uh more packages to be installed i don't think so okay so let's run this code go mod sorry go run main.go and to our youtube bot we'll say query for bot what is the capital of india so it can reply to us the capital of india is new delhi india and youtube bought query for bot what is the capital of china it takes a while because it goes to wait and then goes to voltram see colossians beijing china so as you can see our bot can understand anything you know it's really really powerful so let's say query for bot who is president of india at youtube query for pot who is the president of brazil so as you can see our bot can do anything it can basically uh find the answers for all of these very difficult questions uh that and uh difficult in the sense not for human beings or sometimes even for human beings because i didn't know the president of brazil is right so yeah you can get all of these answers from using your wolfram api so i hope uh you learned a lot in this video today and you built something really exciting and this is a very very powerful bot so if you're by the way if you're somebody who's looking for a job in golang uh i don't think there's a project that's better than this to show off your skills right because you're using golang you're using slack you're using uh and these all these awesome packages right environment packages and the json package and you're using um vid you're using wolfram and then the sky is the limit with it right you can i didn't show you how to train your vid bot but you can you know you can basically watch any other video on vid uh there are many videos on that focus on just how to use fit and you can actually you know scale this spot up to a whole new level right so i hope you learned a lot in this video and uh we built a board that can basically do anything right it's an nlp what and it's connected to wolfram so it can understand anything it can do anything so i won't say you can sign anything because we are not trained of it with api but if you trained it really well it would be able to do anythingif you want to take your go programming skills to the next level this is the course for you experienced go developer akil sharma will teach you how to build 10 projects using go the projects go in order of difficulty starting with a simple web server so in this video we learn how to build a very basic golang web server the prerequisite to this video is that you should have golang installed on your system and you should have a very basic idea of how golang works like packages trucks and interfaces and uh you can watch a video on how to install golang if you don't have it on your system and it doesn't matter if it's open to mac or windows the steps that i'll be covering in this video will be similar for all of them so i i'm on my windows laptop and i've opened my up my powershell uh which is basically a terminal for windows and on mac you'll have terminal on opendo you'll have uh your bash or your terminal again so you once you've installed golang on your system you'll have a folder called go so that's where you want to be you want to be inside that folder called go and inside this folder you want to be inside a directory called as src inside this src directory uh we'll create a new directory called go server and we'll go inside this directory this is where we create our code so i'll open this in my code editor which is vs code so now that i'm in my code editor i'm going to go ahead and create a folder called static where i'll keep my html or static files and my main dot go file where all my golan code will reside as you know when we start writing any golan code we have to write package main in the beginning and then we have to import some packages from package main so one uh of the packages that i need is fmt then i need the log package then i need net slash http package which has most of the functions that i need to create a web server and routes right and then as you know for every golang code we have to have trunk main which is where most of the control of the operation lies right now i'll switch over to my draw.i o board and show you what exactly we're building so i thought before we start building any of the functions it's better to show you uh what we're building so we here's our server file and here are the three routes that we'll be building today one is the root route which is just a slash then we have slash hello and then we have slash form when we hit the slash route or the root route we'll just open up index.html file and then we have slash hello uh which will just uh call function hello function and just print hello to the screen and then we have a slash form route which will have a form function associated with it and then that will open up a form.html file for us right so we have to create index.html and form the html files right now and then we have to write these routes inside our funk main and then we have to create these functions also inside our main.go file right so now that you have a 10 000 feet view of what we're doing it'll just uh everything will make a lot more sense so now let's uh switch back to our vs code back in our vs code you have seen that we had worked till this point till funk main now it's time to create two files index.html form dot html in our static folder in index.html we'll write some very basic code we'll say html and then we'll say head and sorry we'll say title here we'll say static website and after the head we'll place a body tag inside the body tag we will have an h2 tag and we will again say static website and that's that's about it in our form we'll have slash doc type html then we have an html tag we'll have a head tag inside the head tag we'll say meta card set is equal to utf-8 slash right so that's what our meta tag does and then we have our body tag which will have a div it will have a form method is equal to post right so we want to post the form and then we will have slash form right and then we have our label uh i'm i'm assuming that you already know uh html so i'm not explaining a lot of things right but anyways this is the name field that we want the user to input right so we'll have input name is equal to name and then you have type is equal to text and you can also skip this part if you don't really uh you know want to bother about html and then you have label then you have address then you have your input name is equal to address and type equal to text and value nothing right and then you have your end code type is equal to your submit button value submit so a submit button which will have submit written over it all right and this completes our form that we want the user to fill right and now we want to start wiring up our main logic which is inside the funk main so inside funk main we'll have a file server which is basically uh a function that we get inside the hdb package that we just imported so let's say file server where s is capital so make sure you say that and here uh you have a short form assignment operator which basically declares and defines a variable right so with colon and is equal to and then you have http dot directory dot static slash static i meant so we're telling uh golang that we want you to check out the static directory and now golang automatically knows that it has to look at the index.html file because uh as you know php golang node.js all of them look at the index.html file right that's what they're trained to do as servers and now you have a handle function inside your hdb package right and so i want to start handling my root route which is just the slashed out so how do i handle it i say send that to the file server function that i just created which is you know just on top of this and then you have your http dot andrew funk which handle funk is another uh what he called function that we get inside the http package and now i want to handle my slash form route and you have form handler right so we'll create the form handler function shortly and then you have another handle func where we'll handle our slash hello function right slash hello route that which we'll call the hello handler function so far so good i've already shown you what slash hello and slash form are supposed to slash form will show us the form which is from.html just the slash will serve as the index.html file which i've shown you how it will do that and slash hello will just print out hello to the screen and we'll have to create a function called hello handler for that and now let's also print out what will be printed out when our server connects so server.port 8080 and right so if you want to put new line you have to use printf which is inside the fmt package that we've just imported now let's handle our server so we uh you know use the listen and serve function inside the http package so as you can see hd packet is very important and this will create the server so this is really the heart of the software that you're creating right so they can be uh the error can be there or it could be nil so one of these two values will be assigned to err which is the error so now let's handle the error if it's not equal to nil then we want to do something so we want to log dot fatal error and this is where we used our log package to handle or to you know log the error so so far so good with the main.go now we want to start creating our main functions so first we'll create the hello handler and func hello handler this usually has two things so one is w and the other is r right so w is http dot response writer so as you know with any api or any route you'll have either a response and a request so request is something that the user sends to the server and response is what the server sends back to the user so we'll keep that value in w which is the response and for the request that the user will send which will be in http dot request this star is a pointer so r is basically pointing to the request right so yeah i'm assuming you have basic idea of how pointers work even if you don't uh it's okay i think you can just follow this video right so as soon as we wrote funk uh hello handler you can see the squiggly line below hello hundred went away because now it's uh it knows what to do when it uh you know encounters this route now let's start writing out our function so url r is as you know the request so when the uh user sends a request which will be in the form of like let's say slash hello right so what you want to see is if user dot if the r url dot path is not equal to hello now we're sending the uh the request which is slash hello to the hello handler but let's say by mistake something comes here so now we want to check if uh you know the path is not yellow handler then we'll do something we'll say sleepy dot error w slash 44 not found and http dot status not found all right and we'll just return from the function and then if r dot method not is equal to get so we want only uh like when you type slash hello in your browser right that default by default is a get method right and we don't want people to post anything to slash hello we want people only to get and in the sense just print out hello right that's why we're saying that if it's uh not get then again you'll return an error http dot error which will be w again and method is not supported then you have http dot status not found now again status not found is again inside http packet so you can see how important that is and then we'll again return from this function if this is the condition but the ideal condition would be that we want to just print to the screen which is f print f so fmt by the way has a lot of these uh you know functions like printf print ln fprintf right you can check them out and they're all for very different things and so we'll say hello and that's what our hello handle will do now there's this quickly line below form handler so that means we want to write a form handler function so let's start doing that so we'll say funk form handler w http dot response writer and our asterix http dot request now uh you're going to be using this very often so just i mean it's the same syntax so uh you can keep it copy paste it somewhere and then just keep copy pasting it that's completely all right and again we'll have the same thing if error parse form so you want to parse a form right uh we want people to submit something in their form their html file and there will be a post request and they will then that will parse the form error not equal to nil basically if there is error then we want to say print fmp dot f print f w error okay didn't we look done so this is just basically printing out the error and here we'll say f print if w comma post request successful which is the ideal scenario which is where you want to be and we'll say name is equal to so whatever we'll fill in the form right you remember the form so whatever we'll fill in the form uh we want the values to be taken into these variables so r dot form value name so we want name from the form to come to uh name and then we want address to be equal to r dot form value address and we'll say fmt dot f printf w comma name is equal to percentage s new line comma name and then we say fmp dot f f printf is basically printing it on the screen print f comma so whatever the the user has written so we're just going to basically um printed out here now uh you must have seen that there was a squiggly line below and a name and then once we used name out here the squiggly line went away because golang tries to tell you that you're you've defined this variable but you're not using it so that's an error in golang and this doesn't happen with javascript and you can have like millions of variables that you never end up using and that's a problem right uh so that's a nice thing about golang that it catches all of that and then you'll say address so now the squiggly line below address is also gone away now this completes our function so let's uh head over to the um powershell and check it out if it works so back inside our terminal or powershell we're still inside that folder go dash server where we've written all our code and now we're going to run a command called go build which will create a binary executable file it'll be a dot exe file because i'm in windows and um now i can run go run main dot go so we have given our main file the name main.go but you could have named it anything else but main.go is the usual accepted standard right so that's why we named it main.go now we're going to run that code and it's going to say starting server at port 8080 because that's what we had written if you remember in our funk main uh it's it's given me so it's showing me a pop-up which is asking me for my permission for my firewall so i'm going to allow access you might not see that in your in the screen recording software probably now we'll have to head over to our browser to see what's happening out there so let's go to our browser and here we'll open a new tab we'll say localhost 8080 now you remember we have three uh routes we're handling three different routes right so one is the route route which is this just the slash then we have slash hello and then we have slash form.html right so we have those three uh routes that we're handling so slash we're handling uh using file server and then we're handling hello using hello uh hello funk handler uh the function hello handler function then we're handling slash form using the uh form handler function right so in the diagram if you see this right slash hello slash form and then with slash we want to open up the index.html file we just written static server and that will be printed to the screen and then we have slash hello where we just want to print out hello to the screen and then we have a slash form where we open up a form from the html file and then we'll have we'll fill up the form and then we'll you know post to the server and print out something to the screen again all right so let's uh start off by checking out the slash route and see what happens it says static website right which is exactly what is written inside the index.html file and if we say slash hello uh the hello handler function will be called and you will just print out hello uh to the screen and then if we have form dot html i'll just enter my details here and submit so remember it'll say posts request successful because that's what we had written in our code right inside the form hillary function and after uh you know you submitted those details it's just going to print out those details to the screen that's all it does so f printf name and f printf address if you remember writing that right so it's just printing out those values to the screen that's what our simple web server in golang does in this video we'll build a complete crud api using golang and we'll have something called as a movie server which will give us the list of all movies and we can create update and delete as well that's what crutch stands for and uh this diagram is a 10 000 feet view of what we'll be building so that once we start coding you won't have any um confusions right of what why we're doing certain things so there won't be a database that's why i put a big cross here that we are not going to use the database we'll instead use trucks and slices to actually perform operations on the data inside the server itself and uh we'll be um serving it on localhost 8000. we'll be using gorilla mux and gorilla mux is an external library so i'll show you how to install it as well and so we'll have five different routes so we'll have get all route we'll have a get by id route create route update route and delete route and that's something you need to remember because uh once we start coding you'll understand why i have shown you this diagram so every single route will have a corresponding function so if it's a get all route it'll have a get movies function if it's get by id then you'll have a get movie function uh without the s and then if it's a create route we'll have a create movie function and so on for updating delete as well right now there are two types of endpoints slash movies or slash movies by id and we have to use them depending on what we're doing in the sense if we're creating then obviously it's slashed movies if you're updating then obviously the id is required so it has to be slash movie slash id right then there are methods so there are get methods for get all and get by id we'll use get method for create we'll use post for update we'll use put and for delete we'll use the delete method and we'll be using postman to test all these endpoints using all these methods right so um what we'll start doing now is we'll start first we'll create a directory for uh keeping this project and then we'll start writing the code and then i'll take you to postspan to test all the apis so the prerequisite here is that you need to have golang installed on your system uh now i'll see you on the powershell so now we are at our powershell for windows we have powershell for ubuntu or mac you'll have your terminal uh is the same thing and the commands that i'll be writing here will be exactly the same for uh mac and ubuntu as well so you don't have to worry uh now the prerequisite like i said is that you should have golang installed in your server on your system i meant and that means that you'll have a folder called as go in your system right so you have to go inside the go folder you have to go inside src if you don't have src then you can create src but you'll definitely have been in uh package i think so you can create the src folder and now you're inside the src folder right as you can see here uh now we'll create a directory called go movies product and we're going to see it inside this directory right and like i mentioned in the beginning of the video that we'll be using gorilla marks now gorilla mux is not part of the main package that you get with golang right so it's an external package so uh the way to install that is using goget and you have to put the github.com uh link for the same right so the link for gorilla is gorilla slash mux and then github.com then you use go get to get it and then once i hit enter it's going to install it or in my go moviestrad folder now i'll open up my code editor window you could use notepad plus plus i'm using vs4 in this video so i'm going to open up this folder in code plus in vs code like i said and i'm going to try and shift to the visual studio code so i think now you can see vs code on your screen as well and here we'll create a file called main.go now this video is a beginner friendly video so i'm not going to have different folders and a very complex project structure which will have routes and controllers and models and database and all of those files and folders because that will uh you know i'll have to configure the go path i'll have to configure the relative routing and all of those things so i don't want you to be confused if you're a beginner so if you've just learned golang and you just want to get your hands dirty with building a server and building a rest api this is the right video for you so i'm going to try and write everything in the main.go uh file right so so that you don't get confused and this is also why i'm also not using a database and i'm using just structs and slices to actually manipulate the data inside golang itself and so let's get started so as you know that when we write the main.go file the first thing that we have to write is the package main right so and then we start importing the packages that we need so i know that i'll be using fmt because i'm going to be printing out stuff like your server is connected and that kind of stuff i know that i'll be using log because i want to log out the errors if there's any error for connecting to the server and then i'll be using encoding json or by the way all these are part of the package main so you don't have to really uh you know worry so encoding slash json uh i need this because i want to encode uh my data into json when i send it to postman and then i need math slash random we'll be creating uh so let's say the user adds a new movie to this movie server so we need to create a new id for it and that will be created using math.math random so that's why i need that and then i obviously need net slash http because this allows us to create a server in golang so that's it's quite important obviously and then you have your string conversion uh because the id that i'll create using math.random will be an integer and then i'll have to convert into a string so i'll use string and string convert and i'll use itoa to format the the integer and then um you know convert into string so and then i'll have the external library that we just installed which is gorilla marks so you'll say github.com and slash word class remarks now you'll get a quick line for all these packages because uh you have imported them but you're not using them so golang knows that and golang is going to trouble you till the time you start using those packages and which will be quite soon for us so we'll start using them soon now uh if you remember i told you that we won't be using a database we'll be using structs and slices right struct is basically like an object in um in javascript if you view javascript or java or any other language it's like an object and you're going to define you are going to have almost like key value pairs and you're going to define uh you know the types of data inside that so i'm going to have a struct of type movie and i'm going to have uh start of type director okay and movies and directors are going to be associated in the sense that every movie has a director that's how they're going to be associated so movie will have multiple other things he'll have an id which will be string right and then you put this character which is i think called carrot not sure this is directly below the escape button on your left on your keyboard and then you say json and then you say id within double quotes then you have isbn which is basically just a number uh assigned a unique id assigned to a film and then you have again those characters and then you have json and isbn it's right struct here then this quickly like hopefully go away and then you would have the title of the movie obviously the movie has a title right and you'll put string here and then you put a json and then you'll say it's title then you have to say director star director and json and star is a pointer as you know uh so that means if i create a struct call director it will be associated to movie struct and with director what i'm saying is that director will have the same values that i'll define inside the director right so these are strings idea has been entitled strings but director is a type of director which is the struct that i've defined which i'm defining right now and director will have first name which will be a string json and hostname and we'll have a last name so again djson right so when we send this data using postman we'll be using isbn id title and director in small with small you know what do you call it small caps same with first name and last name that's why we're defining json like this so that we're able to encode and decode the json when it comes from postman and so we've defined our two structs and like i said movies are associated to directors right every movie has one director and then we'll have our so we'll define a variable called movies it will be a slice of the type movie this right so because we'll be using movies very often now you'll see why uh i won't try to explain it i'll just show you uh instead so we as you know every golan code every go file has funk main right in funk main you will have your uh so in golang i'm sure you know that you have colon is equal to which declares and defines the variable at the same time so you'll have much dot new router new router is a function inside the mux library inside correla so r is now your new router router and then you'll have r dot handle funk and you'll have uh five functions here so let me take you back to the yeah chrome and show you those five functions so we'll have uh five routes as you remember one two three four five and we'll have five different functions right so inside our uh funk main file itself funk main function itself we'll have to define these routes and functions so let's go back to the code window i'm not sure if you can see it yeah so now you can see it so i'm back at the code window and now i need to create five different routes and five different functions right so first route is the movies route i'll get movies get movies will be the function so if i hit the get move slash movies route i'll need to take it to the get movies function which i'll define in some time till the time i don't define it it's going to give me a squiggly and say that you don't have this function and the method i'll be using here is get you've seen this on the diagram that i'll be using get method for getting all the movies right then you'll have our dot handle fun slash movies slash id and get movie so as you can see there's no s here it's get movie get a singular movie and methods again is get then you have another handle funk slash movies and methods is post then you have r dot handle i'm not copying and pasting r dot handle from this line uh i'm typing it again and again because i want you to type as well and that will ensure that you have some muscle memory and then you'll be able to write code on the fly really quickly and you won't make a lot of mistakes so it's always good to write it again from scratch so you have a function here called update movie then you have methods and say put and say r dot handle funk slash movie slash id again we have delete movie dot methods delete okay so we have the functions we have the methods and we have the routes so all of that makes sense and to start the server what we'll say is so first we'll have to print starting server at port 8000 slash n right and i'm going to say i'm going to log out if the server doesn't start and i'm going to put i'm going to use the listen and serve function inside the hd package that i have here http package so to start a server it's very simple in golang right all you have to do is http dot listen and serve that that's all you have to do you have to write the name of the port so i have to put this code in front of it because localhost colon8000 right uh we'll be hitting that address when you start the server so i have these five functions get movies get movie so i have to create all those five functions and i have the method set out here now before i do any of that when we go to our postman and we'll hit the server right when we hit the api uh slash movies and we want to get all the movies in the beginning there won't be any movies so that uh we don't want that we want it to have at least a couple of movies right so that we know that the server the api is working perfectly otherwise we'll never come to know so what i'm going to do is i'm going to take movies struct uh this slice of movies right that i just created here that's what that's what i was saying that i'm going to show it to you very soon so you don't have to worry about it so we have the slice called movies and i'm going to append a couple of movies to it and by the way all the operations that we'll be doing in this and all these five functions will be around uh this slice called movies because we'll be storing a lot of these different movies uh and the type obviously is this this is an entire type right or you can call it a class or an object or whatever this is an entire type and then we'll have multiple movies of this type the complete structure right and then you have uh movies append and then you have movies right because we want to append to movies and you want to append a movie to movies right which will be an object just like this it will be an object a struct and we'll have to define all these things like id isbn titled and all those things so i'll say id 1 also isbn 4 3 8 2 7. let's say title movie one and for director the syntax is slightly different okay so you'll say director and then you'll say ampersand director because we want the reference object we want the reference of the address of director right which is this out here that's how we'll be able to use the pointer director so if you've used pointers in c or any other language you'll just know that ampersand is to give you the address and percentage or so the aztecs is used to access that address for the pointer and then you have uh the directory which is first name john and last name so i have one movie i will create another movie append movies movie object and it will have an id oh just a second essentially some issue yeah so it will be id 2 ispn 4 5 4 then you have your director again first name so what should be a good first event last name let's keep it steven smith and last name because smith i'll actually keep the s capital even with yeah steve s capital i think so like i said we have our movies so when we now hit the get movies function at least we'll have two movies that will show up right so we'll at least know if the api is working and the server is working fine and now let's start creating our get our movies function what i'll do is i'll create the get all movies function then i'll create the delete function and then i'll create the get movie function create function and update function the update function is uh it will look a little complicated to you it will be the most intimidating so i want to calculate it last so that you at least get used to the syntax before that so let's create get movies okay w http dot response writer comma r star http dot request so we point uh passing a pointer of the request that you will send from your postman to this function and w is the response writer so when we send a response from this function it will be w right so we'll say w dot header dot set basically we want to set the content type as json right so we want to work with json the thing is that um the struct uh our golang stack needs to be able to convert the json coming uh into it into uh you know its own format so that's why we have to set this content type and then we'll say application slash json and then we'll say json.new encoder which we got from here encoding json right json this is the same json json.new encoder and you're going to encode w basically the response that you want to send to it you want to encode it into json and dot and code and you want to pass the complete movies slice that you have so like i said you know whenever we uh when we're whenever we create slices we're just going to append um you know a new movie to the movie slice that already exists whenever we want to update anything we'll be uh traversing inside movies and we'll be updating something inside the movies slice as well so movie slice is quite central and when we all obviously when we return uh the list of all movies we'll be returning or resolving basically the entire movie slices at the same time so this is why the movies uh slices at the center of uh this entire operation that we're doing right now uh so you've seen how now you know how you can get all movies right so you basically uh want to you know encode into json and then you want to just encode movies and send the json of all the movies of uh the slice which has the type struct which is struck movie right so all of these movies you will be able to send to the front end or to postman or wherever now we'll create the delete function because that also looks a little easy right and then we'll get into crea get one and create and delete functions so let's delete them now when you want to delete a movie you'll be passing an id of the movie so we'll say w http dot response writer again and r star http dot request you'll have w dot header dot set again the same thing content type and you want it to be application slash json and now i'll get some params right so the id that i'll pass from my postman which will will go as a param to uh this function create movie and that param uh which will be the id will be present inside mux dot vars and inside the response sorry the request which is r so it will be part of the request right the pointer to the request i'm sending out here so in params now i have the now i'll be able to access the id so what i'll do is i'll range over movies ranging over movies if you used javascript it's very similar to like for each basically so all you're doing is you're just going over all of the movies and you want a put you want to find a particular movie and uh now what you want to do is if item dot id or the id that you pass so you'll say that delete uh the id uh two in the sense the movie with the id2 right so the id which you now have uh right access to which will be params id so you know that we got params we got the id that you sent as a request to this function will be inside params and will be inside id so you'll have access to that particular movie uh that particular id i mean and um and inside movies you will go uh through all the movies one by one and each of the movie will be inside items so item that with item.id you'll be able to access each of the ids of the movies of each of the movies right so if uh the item dot id of a movie which is inside our uh movie slice is equal to the id that you just passed as a pronounce to the request then what should we do we should take the movie slice and we should append basically we want to delete it right so we appending it i'll show you how you can delete something by using append so we'll say movies and index so for range for a range function right you have to pass index an item index is like you know i is equal to one well this very much like javascript like so so for index you have i so i uh you know starts from zero and goes to a particular value and item is actually the item so if you used a for in loop or a for off loop you would know that you can access or iterate over the exact items itself and in go like you can do both at the same time and you'll have movies index plus one and dot so what you're doing here essentially is whatever id that's matching right now that you want to delete it's going to basically take that and directly append all of the other uh you know data which is basically index plus one all of the other data is going to just append it in that place in this place so that means this movie now won't exist it's the id that you just passed with the index it won't exist because in in place of that the entire movie's uh you know uh index plus one after that all the movies that were there they came out here right in this place so the movies uh movies that you want to delete now will not exist so that's how you delete a movie right using a pen now we'll get a particular movie by using get movie function so we'll create the get movie function and again we'll have w http dot header dot set and again your content type comma application slash json then just the same way we did with a delete movie uh you will get params the id in the params right in the same place exactly where r where r is the request that the user sends and mux is the package that we're using for creating these routes and vars is inside mugs right which helps us to uh get access to the all the things and uh requests so basically the params and uh then we'll loop through the movies one by one so if i want to get a particular movie from the slice of the movies that i that exist uh with me in golang all i have to do is i have to go through all the movies and then find that one and then encode into json and send it to the front end or to postman right so here we'll again use the for loop just like we did in delete movies uh but there'll be a difference here instead of index we'll write the blank identifier because we don't want to use index because we won't be using index right and if you don't use something in golang you have to use the blank identifier otherwise golang will give you uh those squiggly lines and give you an error that you've defined this variable but you have not used it right that's why we have to use this uh blank identifier now we'll range over the movies and we'll say if item dot id is equal to is equal to parents id right so inside params i have passed an id so it's going to try and compare that with item.id because it's going to range over all the movies one by one and each movie will be inside item and so we'll have the access of id inside the item and that will compare with params or id that just passed and if they're equal then you just have to return it that's all you need to do you don't have to do any other operations so you say new encoder w dot and code item and then you'll just return now uh i'm sure now you can see why i showed you the delete function uh before the get movie function right and that's because in delete function we we used the range uh but we didn't have a blank identifier if if i would have used a blank identifier directly then you would have gotten confused so that's why i want to show you the delete function before now in delete movie once we delete the movie i think it's better to uh also return all the existing movies after you've deleted that movie so what i'll do is i'll uh try and return the remaining movies as well so i'll say new encoder w dot encode movies just like i did in get movies right json.new encoder w dot encode movies right and then get moving we're just sending one particular movie which will be the item as you know that with range you can access each movie using the item right so we're just sending back one movie whereas with delete movies we're sending back all the remaining movies with get movies we are sending back all the movies so get delete get movie i'm sure these are clear now now we'll take a look at create movie so we'll create create movie which obviously is the most important function because you want to create movies it's going to be a post method response writer and r star http dot request the spelling of response is wrong so it's giving me a squiggly line response it's best to keep uh looking at this quickly line so that you can handle all the errors during while writing the code itself so now you can see that i none of the functions have a squig line anymore except update movie because you've not defined it yet so that's why there's a squiggly line there and we have used all of the packages as well so those quick lines have gone except math random and string convert that we'll be using in update movie and update movie is obviously the most uh intimidating function so i have not shown it to you yet and uh that's why we look it at the last and now we have create movie error dot set so this is something that we do every single time right content type comma application slash json then we'll define we'll define a variable called movie of type movie and you'll soon see why and we'll create a blank identifier again we'll decode our dot query so uh while creating a movie we'll send something in the body we'll send an entire movie like this an entire movie like this we'll send it in the body in postman so we want to now decode that body right we want to decode uh that json body and we'll say decode and right so we'll get that value here in this and movie right after decoding it i will say movie dot id so this is where we'll use your string convert and your uh math.random because you want to create a new movie all right so to create a new movie we also need to create a new id which will be completely random id so what we'll do is we'll say random dot which is a function inside random math random library package and we'll say one one two three four five six seven eight you can put as many zeros as you want so i want to value between zero between one and this uh maximum value to create a random value right and then i'll have to now format it into string so i'll say string convert dot ito a which is a function inside string convert package and that's how i'll get a new movie id so i'll say movies is equal to append uh like we saw how uh with delete movies you could append right and now with create movie also you want to append uh just like we did when we created a new movie we want to append the new movie that has just come to movies that's all we want to use it's very simple so we'll say append and we'll see movies comma movie because the new movie that has come out come from the body is now inside uh this movie which uh you know uh we decoded from json into now a format that is readable by golang and it will now look like this it'll look like a struct right so that like we said movies comma and the entire movie so that's what we're doing here essentially we're just saying movies and comma movie that we just received from uh the body that the user just sent from their postman and now which has been converted into a formatted by calling right so uh really simple now since we have appended it here now we want to also return this movie that was just created just to tell the user that hey you know i have created this movie so you don't have to worry encode and movie so the movie is now created now comes the most intimidating function which is update movie function i'll start writing it out update movie and here uh we'll be passing an id right so you know how to get the id right you'll get it in params which will be inside mux dot vas and inside r right the params will be there and then we'll have to again range over all the all the movies and then what we'll be doing for updating movies is we'll first delete that movie uh for the id that you'll send and then we'll just simply add the new uh id that uh uh the new movie that we'll be sending from postman so this is not obviously the right way to do things when you work with databases uh but we're just doing it here since we're not using a database we can get away with that we'll just delete the id of the movie that uh the the movie with the id that you send from postman and then we'll uh uh you know just add the new movie that you'll send the new structure in that same place we added there so uh i hope that makes sense or maybe i'll should i just write some pseudo code and so that it becomes really clear to you so first what we'll do is we'll uh set our uh content type which we always do right and then the next step will be that we'll get access to our params then we'll loop over the movies or we'll range over them to introverted movies then what we'll do is we'll uh delete the movie of of uh the id sorry with the id that we have sent suppose we'll delete it and then we'll simply add a new movie which will be so instead of actually updating uh that particular record in a database we're just deleting it and then just adding a new record from the body that you're sending which is nice little hack and something uh that you shouldn't do when you work with actual databases it's just to show you right now so this is the pseudocode one by one let's start writing out code then right so now we want to set json content type how do we do that we do that by w header dot set content type exterior and we will say comma application sorry application slash one and then we want our parents right so to get parents we'll say params dot where's r we've been doing this till now now we're going to loop over uh the movies and we're going to delete the movie and then we'll add a new movie so we'll do all of those three things now at the same time so we'll say for index now we want to use index in this case so we won't use this blank uh identifier because you want to use index we'll say it's equal to range movies and if item dot id params id what should happen so like i said we'll first so we'll delete over the movies uh using range and then we'll find that uh movie in our movies slice then we'll delete that particular movie with the id that you've sent so if you found it with the id that you've sent now we delete it so we'll say movies is equal to fn so we'll write the exact same line that we've written in delete movies to delete it so we'll say in a inside a pen we'll use the exact same syntax so let's say movies and index comma movies index plus one let's say dot dot right so let me see if that's what we've written earlier yeah there were no mistakes earlier so it's the same thing now we'll say where moving of type movie now because we want to append that movie so that's why we're going to uh try and follow the same code that we've written for create movie and we're essentially going to almost we can copy and paste this whole thing but i'm just going to write it again right so so like i said you know we are adding a new movie the movie that we sent at the body so we'll say equal to json dot new decoder so the id that we have passed so this is the only step that's different from create movie right because we want to have it in the same id we want to use the same id so let's say movie is equal to append movies let's say json.new encoder w dot and code movie because you want to return uh the movie to the user to tell him that hey i have done what you wanted me to do i'll remove these comments since now you already know how this is supposed to work now one thing that we've not done inside update movie is w http dot response all we have to do now i think is right return here and then we're good to go i don't think there are any issues or errors here so i can go ahead and compile this code maybe right so let me take you back to the powershell uh how do i yeah so i'm back in the powershell now so i'm inside i'm still inside that folder go movies crud and as you can see i have that main.go file so all i have to do now is go build i've built it and now we have to say go run main dot it's going to now start the server and it's going to ask me for firewall access maybe you don't see it in your screen because it's a pop-up so i'll say allow access so yeah so now it's running on server 8000 uh now let's go head over to our so let me see if i can do that or i'll have to maybe pause the video and then show you post man yeah yeah i can show you postpartum yes i think you could see it now uh i'm using obs so it's difficult to switch between tabs actually in obs screen recorder uh now i have created this folder called rough just for my own use uh you can you can probably create just a new folder and inside this i'm going to create a new folder called go movies inside go movies i'll have a request the request will be get all then i'll have a new request get by id i'll have a new request again it'll be yeah create then update and delete so forget all all you have to do is http slash localhost movies right so you have to write http double slash localhost colon 8000 slash movies that's what you have to write and let's hit the server and voila the server is working we have got our two movies that we created in our posts in our vs code right because we didn't want this to be empty so we had created two movies using append and in our funk main so these are those two movies let's get a movie by id so i'm going to take the same route here i'm going to put slash one because i want just the first movies like i'll get uh just the first movie as you can see right now i want to create a movie to create a movie i'll just say uh i won't give the id obviously because i uh golang will create the idea and so on and i'll go here and say the body and i'll say raw and i'll say json and now right i'll just try and call i'll just copy paste this one little from my get all i'll copy and paste one movie here in the body i'll change the id i'll say seven else this i'll change the number something else let's see movie seven and the name here i'll say okay sure so it has added that movie called seven but it's not sending me that uh movie seven it should have sent me the 27 here so there's something wrong we'll have to oh sorry i'm still on get so remember to switch to post method here right so when you say send it gives you the movie that you just created which is this movie 7 right and id there's no point of sending id because id as we know it's going to create on its own so i was wrong when i did that so even if i create one more it's going to create one more id with the same values so now when i get all i'll see four different values right now let's try and edit one of these so let's update uh first let me just copy this whole thing here and switch this to put and then we'll put the id of one of the movies here let's put this id here and update right and then we'll have to say send something in the body which will be the new movie the new movie can be copied from here and we can change some of the values like we'll put it on and i'll just say s because i can't spell shot maker say something else here isbn and so let's see what happens so yeah the movie has been updated the movie seven had first name akil sharma now it's just has arnold so even if we get all we'll be able to see that the movie seven has uh so there's one movie with atletico there's on one we with arnold s because we had created two right in the beginning now let's try to delete this so i'm going to first copy this thing and put in delete and then i'll put the id i'll go back here i'll get the id from here so now it's returning me the movie that has been deleted which was movie seven on test so now when i get all i i won't see that movie hopefully i'm still seeing that movie actually why is not working oh sorry it's on get i'm i again i made the same mistakes i have to uh use the method delete for it so don't make the same mistakes that i'm making all right so now there are only three movies so it's returned me all all the movies uh that are now left right so there are only three movies left even if i say get all there are only three movies left let's delete one more let's read this one also so that only two movies will be left so yeah only two movies are left now right so remember to change the method when you're using postman we'll be building a bookstore management system using golang so we'll be building some cred apis and these are beginner friendly you'll be using mysql database we'll be using the gogorm package to interact with our database and then we look at json marshalling and marshalling and the biggest change here is that we'll have a proper project structure in the sense we won't be writing all of our code in main dot go file we'll have a proper project structure which i'll explain to you shortly and then we'll be using gorilla mugs so with project structure this is what we're going to do we're going to have two main folders in our project one will be the cmd folder the other will be the package folder the cmd folder would only have the main.go file and the package folder uh will have the config folder controllers folder models folder routes folder and utils folder so we'll have six sorry five uh different folders inside the package folder right inside config we'll have app.go file uh which will help us to connect with our database in the controllers we'll have book controllers which will have the functions that will help us to uh you know process the data that we'll get for as response and also the request that we'll get from the user and the response that we need to send so we'll process all of that in the book controller in the book models in the models folder we'll have book.go file which will help us to create those structs and models that will be used by our database in the routes as you know we'll just write our routes and which i'll get into later on in just two minutes i'll show you what the routes are and in the utils we'll just have uh for uh some code for marshalling and marshalling json from our response and our request right and then these are the routes that we have so we'll have uh slash book slash route uh twice one will be for post and one will be forget and these are our controller functions that i've mentioned here so uh if you post on the slash book route uh sorry i think this needs to change this will actually be get and this will be post all right so if you get on our slash book route you will we'll call the get books controller function if you post use the post method on our slash book route we'll create a book right we'll have to send something in the body and we'll have to uh use our uh json master link and much link to uh you know get the data here to the database and then uh we'll if we do get on slash book slash book id which which we'll pass the book id so we'll get the book by id so we'll have to create function to get a book by id then we'll have our put method for updating the book right and on the same route slash box slash book id and then we'll have our delete uh method on slash book slash id route which will give us the delete book uh the function and controller functions so that's our entire uh you know introduction on what we're going to build and how we're going to build it the next steps include where i'll go to my overdue terminal i'll start these uh different folders i'll create this complete project structure and then we'll open our vs code we'll start creating these folders and these files and then we'll start writing all of that right and before that in our ubuntu we'll also have to install the packages that we'll be using so uh in many of the videos that you'll see on youtube you'll also you might see people first including those packages in their uh files while they're coding and then they'll use go mod id or something like that to install the package that they've used but in our case what we'll do is we'll install those packages beforehand and then we'll include them in our code it's just something that i prefer and i also recommend you also do that so that's that's the introduction and let's get started so as you can see i've opened up my terminal uh since i'm on ubuntu this is a terminal if you are on windows it will be a powershell and if you are on mac it will be a terminal again the commands will be the same it doesn't have to uh the commands won't change so i'm going to go ahead and go inside the folder where i write all my go code where all my go programs reside you can do the same and i'm going to go ahead and create a directory for the new project and it will be called go bookstore in my case and i'm going to go ahead and see the inside uh the go book store and now since we are here we'll have to install a couple of packages right so before we install the packages we'll have to create a go.mod file which will uh crea store all the packages it's almost like the package.json file if you are from a node.js background right so it contains all our packages that we'll be using in this project so we'll first do go mod in it and even if you're not storing uh right now inside a github account i just recommend you use github.com and slash your name or any other name and then slash the name of the project which is bookstore this gives us like a relative route or then or an absolute route based on which we can you know include and import different files into our main.go file so it has created our go.mod file okay and now we'll start uh importing the package that we need so the first package that i need is the gorm package which will help me to interact with my database jinzoo slash form so jinzo is the name of the guy i think just created gorm so we have added gorm and now more specifically i need uh the mysql package inside uh guard because gorm uh is a is an orm right it helps for for golang and it helps you to interact with sqlite and postgres but for this example we need mysql so we're going to go ahead and install that and then uh we need to install uh the gorilla mux package since we need to use that for our routes so i'm going to say go get github.com gorilla slash mux so we've installed gorilla mux as well now as per my knowledge uh these are the three packages that we will require but as we go along uh you know i might find that we need more packages so uh it's not a problem we'll install them uh as we go go ahead so from from what i see what be building right now i think these three should be enough probably uh so let's get started with the actual code now that we have our packages in our go mod file uh go mod file also helps us to uh you know go build which will create the build or the exe file which will uh execute on our uh machine exe if you have windows and dot deb if you have uh basically it's a binary file if you have ubuntu and so we're going to go ahead and open up our vs code editor so i'll say code and space dot and that will open up my code editor so as you can see i'm inside my vs code window and now i'll start creating the folders that we had seen in the diagram and you may have noticed that there's a time delay between when i switch between my google chrome and my vs code and my power shell or my sorry my terminal and that's because i'm using obs to record these videos and it's not very user friendly in terms of helping you switch between the tabs very easily so kindly bear with me so let's start creating the folders quickly uh as i've shown you in the in the diagram we have a cmd folder and we have a pkg folder right these are two main folders inside our pk inside our cmd folder we'll have a main folder and inside the main folder we'll have our main dot go file where all the magic will happen right the main controller the main control of our entire project and inside the package uh folder we have config and we have our controllers then we have so i think by mistake what i've done is i've created controllers inside uh config so i have controllers and then i have models and then i have routes and utils right routes and details so as as you've seen just a second back that i had created controllers inside config by mistake and that's a very common mistake by the way and uh that will happen to you if you're not very careful so please make sure that inside your package folder all of these different folders are at the same level inside the package folder right they're not inside one another yeah that's a very common mistake by the way so let's start creating our files inside uh config we have app.go uh inside our controller i i by the way in the diagram i'd already shown you uh the name of the files as well so we have controller.go to control.go and then inside models we have our book dot go file and inside our routes we'll have bookstore routes dot go okay and inside our utils uh the name of the file will just be utils.com now you know there's so many files right here so we need a strategy on where to begin and where to end the program at so how do we start coding how do we begin this whole uh journey of uh writing so much code right it can be confusing it can be daunting it can be overwhelming uh many times so that's why i have a small strategy for you that will help you understand everything really well what i'll do is i'll start with the routes so i'll create the routes first and uh that will help you visualize the routes where the users will hit you know from their front end or from their postman the user will hit on those routes right so we'll start with the routes and then what we'll do is we'll then write our app.go file which will help us to connect with our mysql database then we'll create our utils file so uh app app.go which is the config file and utilize files are very small files so they won't confuse you too much and the routes file is also very small and then we'll create a main.go file the main.go file all it will do is it will just uh you know tell golang that here in bookstore dot routes is where my all my routes reside so all these files will be really small uh then we'll create our models file which will be slightly bigger and then our book controller will have a lot of code so uh we'll tackle it at the end because after the routes the control will go to each of the functions in book controller file so this is the book controller is what we'll tackle at the end and before that you'll get a little bit of an idea of what we're building so it things won't be very confusing for you that's what i'm uh at least trying to attempting to do so uh as you can see i started coding here i've written package routes and then i've said uh started importing the packages that i'll be needing since this is my routes file uh the one package that i most definitely need is gorilla mux which will help me to create the routes in the first place and the other package that i need is not really a package but i need my controller file here so first just see what this is then i'll try to explain to you what's happening so i'll say akil slash go bookstore slash pkg and slash controllers so this will help me import my controllers folder and uh in turn the file inside the controllers folder as well right now if you're from a node.js background you will be very confused when you look at this right so this is uh this is an absolute path whereas with uh node.js you're used to something like this right so you'll say controllers and that's because routes and controllers are both in the same package called pkg so you would say that okay i just want to import controller so i'll just say like this right but that's not how it works with golang golang has absolute parts and once you get used to golang you'll understand that that's kind of the right even if it looks lengthy but it's kind of the right way to do things right because uh this uh the github.com go bookstore uh till here is the path that we created which was like the absolute part that we created for our project when we were initiating the go mod file if you remember and package.controllers is where you know we'll come inside package and then it comes and controls this is where the controller's file lies and that's what we want to use so it may take you a while to get used to this absolute routing but uh but once you get used to it uh i'm telling you you won't go back so i i am a no just developer i was not just developer i can say for a very long time but once i started using golang i can tell you there is no going right because uh golang is so so much better so you have registered bookstore so i want to create a function called register bookstore routes and this function will have basically all my routes and this the routes will help me to get the control to my controller where which is where i'll have meet the meat of the logic so i'll have router marks dot router right and here is where in this function is where i'll create my handlers so router dot handle func right so if somebody comes to my slash book slash right so i'll say controllers dot create book so i've shown you the create book function right in the diagram i have not written the from function till now but i'll be writing this function in the controllers file and this is why i needed my controller's package on top controllers file on top right because if somebody hits the book uh route i want my controllers.createbook function to handle it and the method uh you know is going to be post here because i'm trying to create a new book so i'm sure that's very clear and then we'll create another handle funk and it will again be slash book slash but this time i want it to say get book you'll get the list of all books for me and the method in this case as you know will be get so on top by mistake i had put two h uh for methods i i removed one of those so just make sure you don't make any uh you know typos or any spelling mistakes then we have another handle trunk where we will handle as you have seen in the diagram before the uh you know the scoring part started we'll have slash book and inside this we'll have our book id right and then you have controllers dot get book book by id all right so that's the function i want to get one book by id and dot methods you know the method would be get in this case all right so i think all clear till now now we want to create the two more routes they will be same slash book and slash book id will be there but there will be our put and delete functions right so i'll say router dot handle func sorry and here also i think the us capital it should be a small queue and then you have slash book slash book id and then we'll say inside my controllers file i'll have a function called update book okay and then the method for this will be put and similarly for our delete route as well book slash book id and we'll have controllers dot delete book dot methods and we'll have the delete method here right so so far all looks great right everything is uh working out pretty fine for now so we have written our routes uh package so if you read this far then you should be proud of yourself i think so now like i promise you we'll write the app.go file which is the inside the config folder right and so we'll come here and we'll uh give it the name config package config sorry it's not capital package config all right and here i want to import just two of my packages and they will both be related to talking to mysql so the first package will be jinzu slash gorm which is my orm and the second package will be the more specific one which is dot github.com slash jinzo slash gorm slash dialects slash mysql so if you go and look at the documentation for uh the corn package you will notice this blank character here and then space and then the uh link right so just make sure you do that as well so once we have imported these two packages uh the mysql package and the gom package now is the time to create a variable called db so the the whole point of this file will be to return uh a variable called db which will help the other files to interact with the db right so we'll say star born dot db and then we'll create a connect function the connect function helps us to open a connection with our database and the database in this case as you know is uh mysql database right so we'll have d comma e r r uh the if there isn't so i'll write some statement here and then if there's an error the error will come inside err if if there's no error and the database connection has open it will come inside d right so i'll be able to access the connection using d so i'll say gorm.open which will help me open up my connection with the database right and here i'll write something so i'll i'll say the name of the database that i want to use mysql because gorm helps me as i had said talk to sql lite and postgres as well but in my case i want to use my sql and here i'll say the name of the user and my password and my the name of my table simple rest and and then we'll write some little lines here which are required by mysql so uh if there is is uh you know an error right which means that if error not equal to null which means that if there is an error so we'll say panic er r and here we'll say db is equal to d right so whatever was in d here that we received we'll transfer that to now db variable and we'll have a get db function which we'll use in other files and it just returns deep so like i said you know the purpose of this file is to return um a db variable that will help us to talk to the database other files can talk to database easily now uh as you can see i have not written some code ahead of this part right so for mysql to connect we have to write some things after my username my password and the name of the table so that needs to be care set is equal to utf 8 just make sure you copy this exactly and you have parse time is equal to true so this is some requirement by mysql right so you have location right so these few lines you have to write and then your app.go file is complete now the next code that we'll be writing will be our utils dot go file so when whenever when we start writing our book controller we will be using uh you know we'll we'll need data that is unmarshalled data so we'll we'll receive some requests from the user right and it will be in json but we need to unmarshal it to be able to use it in our controller so we just need to write a one one very small code here to be able to unmarshal uh the json that we'll receive from the request so it's going to be very simple we're going to call it utils package utils and we'll import a couple of packages one is called encoding slash json right the other is called i o slash i o util and the third is called netslash http right and here is where i'll create my function and the function is called parse body that will help me uh to pass the body uh especially in the create function in the sense when i'm when i'm trying to create a book uh you know the create book function in my controllers i will receive somebody in the request right so i need to parse that body because that body will be in json so i need to be able to unmarshal it so i'm just creating one small function to do that right so i get the request and a pointer to it and i take that in r so i'll be able to use r to access the request that i've received from the user and i'm sure you know what a request is you know request has that body that we're sending of the uh the book right and then you have x and you have uh interface so i'm sure uh you know you know basics of how interfaces work so we'll say body and error is equal to ioutil dot read all all we're doing is just reading the body right and if there is no error so error double equal to nil then we'll say error is equal to json dot then we'll start unmarshaling it basically on marshall there's a single l right and we'll say byte and body comma after body you say comma x so just one thing guys the x is a small x not a capital x by mistake i written here capital x just make sure of that and then error not equal to nil and then we'll just return right so even uh this looks like it's complete right and so your utils file is complete and your bookstore routes file is complete now we want to start concentrating on our app.go file yeah sorry the adword file is also complete so now we want to start concentrating on our models file right which is slightly uh more advanced so but let's start anyways right so we have package models we'll call it and then we're going to import as you know we'll import our gorm package first github dot com slash jinzu slash form and there's one more thing that we need to install or import and that will be my config file that i just created right because the config file helps me to connect with my database so i need that here so i'll say github.com right so let me just be sure that yeah this the routes required controllers and the app.go file required gorm and the models required config yeah so i think yeah so we're on the right track so we'll create a database uh the variable called db gordon.db you've seen this already in the config file and we'll create a struct called book structs basically are based on models and a model is something that you know gives us a structure to help us store something in the database so in this case we'll have name because every single book will have a name right and then you put these back two backticks inside that you say gorm then you say json name let me say author and you say string again so name of type string and author of type string and then you say gorm sorry you'll say json and you'll say here author okay and then you'll say publication and string backticks again json again and publication so let me read through it and make sure everything is fine gorm json alright author and publication right name author and publication so we have three things and uh so usually almost like almost always you will find this that we have to whenever we working with databases we have to edit our database so if you've seen the golang to-do list video that i've created so a few days back you must have noticed that init function so here also we need to have an inner function that will help us to initialize the database in the first place so config.connect this is the function that we created together just some time back where which is the connect function which helps us to connect with the database that's inside the config folder you know that already and db is equal to so whatever we get from that um uh you know config file uh by calling the getdb function which we have created together just some time back get db function inside app.go as you can see this is your getdb function which returns just the db which uh you know we had connected to the ddtv right and so that's what you get here inside db so here also you have a db variable where you're just storing the dv that you get back from the config file right so till now i think everything should be highly clear and then we'll just auto migrate it with a book an empty work okay so all good till now uh now you know the control first is in the routes right here in the routes and then the routes basically give the control to the controllers and the controllers will give the control to the book.go which is basically the models right so that's how the flow works in the sense the user interacts with the routes and the routes send control to the controllers where we have all our logic which will write in some time and the controllers then have to perform some operations uh with the database now the the operations of the database have to reside inside our models file which is book.go in this case so that means we'll have to have a different function for the different controllers that we create so we need to have a create a create book uh function here we need to have a get all books get by get booked by id and delete book so we need to have all these different uh functions here right so uh now we have two options one is that i start creating those functions directly or i create the main.go file and then that will give you more clarity and then we create the functions that are required for database right so i think i'll create the main.go file so that you have a little more clarity so let's create the let's go on main.main.go file and then we'll come back to the uh book.go file as well now the so yeah so we have one more option one is that i start creating the controllers and then once we are writing the function the controllers then i'll start creating the model functions but that may confuse you so that's why i want to create the model level functions first which talk to the database right and then we'll have a corresponding function to that in the controls so that i think i feel at least from my opinion that that will make things very easy for you so anyways that let's write out our uh package main file inside our package main file we'll import log because i want to log out if there's any error we'll have nest slash http so as i told you earlier that in our main file all we're going to do is we're going to create the server right which will be which will will also define our local host that's the first thing that we'll do the second thing that we'll do is we'll tell golang where our uh routers reside so basically all that main.go file will do is tell that you know bookstore.routes has our routes so please look there because i don't want to write all my routes in the main.com file right so that means i need my gorilla mux package here slash marks sorry there's slash here and then i need my uh mysql package here github.com dialects slash mysql and then there's something else i need here i need to import the routes right so i know that the routes is inside uh package folder inside that is routes folder so i need to again use my absolute path which will be github dot com slash hill slash go bookstore slash package so let me make sure if in my uh yeah so here also it's correct package config right so yeah so we have google bookstore slash package slash routes so we need the routes here like i said and now you know that inside uh a main dot go file you always have funk main so let's create the function which will basically have mux dot new router so we're creating an r variable with which will initialize the router here and we'll say routes dot register register bookstore routes and we'll pass r to it so if you remember in our routes we have some a function called as register bookstore routes here it is registered bookstore routes and we are passing the router to it r which is the router that we just created inside main.go file we are passing it to it and then we are handling the functions using as you know controllers functions right so the r that we are passing here becomes router right which is of type mux dot router so i hope everything makes sense now if there was a confusion earlier that i'm sure everything is making a lot of sense now so http dot handle comma r right and then you say log dot fatal so like since this is a slightly big project in terms of different files and project structure so i uh you know it's very important to know what's the order in which you want to build the files right so if if i would go in the order that's comfortable to me then you might get confused and so that's why i'm having to pick an order which i will make a lot of sense to you right so you'll have listen and so which helps us create the server in the first place right and these brackets i'll say localhost nine zero one zero and comma r so uh by now i'm sure you know that listen and serve is a function that helps us create a server and we pass to it this which is uh the the post port or the address on which that we want to start the server and it's inside the http package which we have here right so and if there's an error it's going to say log it's going to just log it out right so that's our main.go file now let's come back to our models file which is book.go so uh i'm going to start creating all the functions that i need to talk to my database uh things might look very i won't say very what things might might look a little confusing to you right now but when we stop when we finish writing our book controller file it will make a lot of sense to you so the routes from the routes the data uh you know the control goes to the controllers like i said and the controllers there will be different functions that i've shown you in the diagram that will have uh like you know create book and get booked by id get books right uh all of those functions will be there and then those functions will again to in order to connect with the database not to you know uh make changes in the database they have to go through these models right so we we have to write these model functions and that's what i'm creating right now out here we can do this like i said after we create the controllers as well but it may get confusing for you so that's why i want to you know write these right now so we'll have a create book function and we have something called as a db right which we have created here on top db so db is what helps us to talk to the database so db.new record now new record is a function that exists inside garm that's why we're using god because we don't have to write those queries for uh mysql the query part gordon will write which is an orm which helps us to talk to uh the database we have to write these simple functions like create a new record those kind of things right so we'll say dv dot create ampersand b right where b is something that we'll receive which will be uh of type book right and what we're going to return is also of type book so that's why we have a star book here so we are going to return b of type book right so we receive something of type book which is b so we create that and then we also return that same book that we created so that's why we have star book out here as well now i want to create the get all books function that will help me clear all books so return all the books that i have in my database and here we'll have books now i'm using a slice here because i want to return a slice or a list of the books that i have in my database right so we'll create a variable which is books which is of type slice book where b is capital just make sure b is capital and then all you have to do is db dot find books and then you return books right so you'll be returning the list of books which is slice right now i want to create a function for getting a book by id so that means it needs to take an id first obviously that's very clear which will be of n64 there's no space between ninten64 my bad and so these two things have written star book and start start gom.db don't worry about that right now i'll explain to you as we go along so we have where get book of type book okay and db is equal to db dot where w is capital by the way and id equal to id right so we are basically running a where command in mysql where we are saying that where id is equal to id right then find that book find and get so not only are we going to just return uh the book that we found right now from the database but we're also going to return the db uh variable as well so that's why we have the book that we're returning get by id the book that we're returning with that particular id in our database and we're also returning the db uh variable that we had created which was of type coord dot db right and then we have a delete function func delete book id again is int 64 and there is book before it book of type book so db.where where it helps us to find the book with the id which which i've just shown you some time back question mark comma id right so uh and get get booked by id i take an id where d was small now in this case i'm taking id reduce capital and then i'll say dot delete and bracket book and then i'm just going to return the book so these are all the uh database functions i have now here there will be a big doubt for you you will be wondering why is there no update uh function why don't we have an update function because uh in this video the way update will happen uh in the controller will be that uh we'll find the the book the id that you'll send as the from the the user that the id that we'll receive so we'll find that book first and then we'll delete that particular book and then the new data that the user has sent us to be uh updated so we'll use that to update uh the book and created basically a new data so we don't have uh an update function as such in our you know models we're just going to use uh get and delete and then post create basically we're going to use a combination of those three to update a file in our database so uh it may sound uh confusing to you right now but uh once we build our controller uh file everything will make a lot of sense right so let's start building our controller so we have package controllers and then we're going to import the packages that we need so i i know that i want to use encoding slash json package and the other packages that i need i'm just making sure that the video is still recording because because you know obs obs has a lot of problems and then i want to use the fmt package because i want to print out things to the console then i have my github.com gorilla mux that i want to use dot com slash gorilla slash max that i want to use right and i want to use my net slash http package i want to use string convert package and i also want to use now i want to import my utils and my models so by both my utils and my models are inside my package folder so you know how to do that right github.com go book store slash pkg slash utils right and com then uphill slash go book store slash pkg slash models so i have both my utils and my models right now we'll create new book which is a variable of type models dot book right so in in our model file which is book dot go we have created a struct of type book right and that's what we have been using all this file so uh of type book is what we are creating here we're creating a new book of type book right so model when i say model i'm referring to uh the models sorry with an s i'm referring to my models file and i'm referring to the struct inside uh the book struck book call inside inside my models file right so new book is of type book which is a struct and which has all these different things it has a name and author and publication right and it's called new book i'm explaining to you uh this slowly because controllers is where people get confused right so first uh yeah so here we have our five functions which is get books and create book and get booked by id and update and delete so the strategy that we'll follow here will be that we'll create the get books function first because that's the most easy in my uh x in my you know from my perspective at least uh from you know at least what i think is the get books function is the easiest so we'll build that first so whenever you're building a function a controller function you know that you have two things you have a response writer and a request for request you put a pointer to the request that you receive from the user and then so we have a request in r and our response in w so whenever uh the response that we'll send to the user will be with w so we'll have to return w basically and then we'll have new books models dot get all books now uh the model functions may not have made any sense to you but here it will make sense because what we're trying to do here is uh we have uh you know new books and in that we'll store models dot get all books so models dot get all books is this function that we just created together model.getallbooks right which will just basically find all the books and send a list of the books back to the user right so now back in our books controller we have a list of books inside new books and then we want to have a response json dot marshall new books so we want to convert it into json right whatever we see from our database so that's why i use the marshall function and then we'll use in the header we want to say content type comma json w dot right header http dot status okay okay so basically it will give us a 200 status okay means it gives us a uh 200 and then we say w dot right which is the main thing now which uh you know helps us to send something to the front end or to postman which is the response the response is basically a json version of new books that we found from the database so we're just going to write a response which will basically json right and the list of the books that we found in our database that's all it is and now the second easy function in my opinion is get booked by id so let's create that as well so funk get book by id w http dot response writer and comma r http dot request all right so we'll get access to our r which is our uh request right so inside our request obviously will be the book id right so we want to access our request and we want to access the book id inside our request so book id is equal to vars and book id so we'll have string conversion dot parse paint book id comma zero comma zero so we just want to make sure that the book id that we've received that could be in string right mostly it's a string and we're just passing it to int using the string conversion package that we have imported here and if there is an error error not equal to nil we'll have fmt dot print ln error while parsing that's what we'll return and then we'll have book details comma the blank character and say models dot get book by id and id right so we are getting get uh booked by id models.getbookbiod right which is a function that we created together if we remember let me take you to the models file and show you so inside the model file inside book.gov we have get book by id so we will be returning two different things like you know we'll be doing the book and we'll be returning the db uh variable right and since i don't want to use that use the db variable right now so that's why i'm using the blank uh character here because i don't want to use it in golang if you don't want to use something uh it's better not it's better to use the blank character because if you define something and don't use it golang is going to give you a big error so just make sure you use the blank character here right so uh yeah so i'm going to get booked by id i'm going to get that inside my book details uh variable right and now i want to start thinking about the response that i want to send to my user which will be very simple it will be just json.marshall and book details so to my user i have to send a json response right because i get something from my database i have to convert it into json and then i want to send that to my user right so that's why i have to marshal it into json so now let's start creating my header that i want to set and will be of type content type give type json and w dot write header http dot status okay and then you have your w dot write response okay so i hope this is making sense till now so inside our right header uh we are sending status okay which is 200 that everything worked fine and we are sending the response and inside the response inside rds which is the response we just have a json version of the book details basically the book that we found in the database based on the id right so i am sure all of all of that is making sense if things are not making sense to you then you just you know watch this video slower or you just type it out with me just quote it quote along with me i hope you're coding along but maybe once more you can code long and then uh you know things will start looking becoming clearer to you and if you still don't understand then you can just you know put a comment in the description in the comment box below uh for the video and then i can probably help you out so you have your response writer comma r is your http dot request so this is a quite long video right so if you've reached this far then you should be really proud of yourself model stock book all right so utils dot parse body now we'll receive something from the user right as a request and now we want to pass that uh into uh so we're getting that in json we want to pass that into something that our database will understand so that's why we are using parse body which is a function that we created together inside the utils file right so we're going to say r comma create book all right and then we'll say b is equal to create dot create book so create book right is a model of type uh is a model uh inside the models you have books right so create book is of type that basically and then when we say create book dot create book so i'm referring to the create book function here this one that's what i'm referring to out here okay so we'll have create book.trade work and then i'm gonna i now have to start thinking about my response my response will be json.marshall inside that i passed b so b is something that was returned to me by my create book function inside models let's look at what it's returning to us so it's returning to me the same model that is the same object or same it just created inside the database so it created something inside the database and it's just returning to me the same exact thing so that's what i have access to which is b in this case so it's basically the same book that was sent to me by my uh user as a request right so in the response i'm just going to convert that into json so from uh in the beginning we received json and then we passed it into something that the database would understand we sent it to the database the database sent us that same uh you know record and then that record we are converting that into json right now to be able to send that to our user to postman basically so we'll say w dot write header and then we'll say http dot status okay w dot right and we're just going to write our response to the uh postman right so create book was also uh i feel quite straightforward now we'll work on the delete book function func delete book so which will have w http dot so let me just check if the video is still recording i'm not sure yeah it seems like it's still recording anyhow so in our delete book uh function so as you are seeing right now that all of these functions are talking to another function inside our models right so same similarly with delete book we'll be talking to the delete book function inside our model which is book.go so let's have responsewriter and comma r which will have a pointer to the http dot request that you'll get from the user and then we'll use vars again to be able to uh you know access the request that we've received from the user and now we want to access the book id where's both id right and then we have our error so string convert so basically if you're not understood by now this we're doing the exact same step that we were uh doing in the get book by id so because we need uh to access the request then we need to access the book id then we need to convert that into hint which will uh you know do by string convert.parse and package and then we'll also print out the error if there was some error right while passing so we're doing the exact same thing steps there's nothing new here parse hint and book id comma 0 comma 0 and if there is an error which means if error is not equal to nil then we'll say fmt dot brain talon and here we'll say error while parsing all right so that's great till now and then we'll have book is equal to model start delete book id so you know this function write delete book which we have created together in the models file delete book it takes an id and it just deletes the book and then returns the book that it just deleted right so the book that has been just returned to us will be inside the book variable all right now we have to start thinking about the response and how we have to send it to our user inside postman so we'll say json.marshall the book that we received from our database function right now that needs to be converted into json so and now we'll start creating our header and we'll setting set or header content type comma pkg location slash json w start right write header http dot status okay w dot right and this is the response the last three steps are the same for almost all functions there's nothing new there now there's only one function left to go which has obviously the people find it the most complicated function which will be the update function and it will have some aspects of all of the different functions that we have seen till now it's also the biggest function so update book is the biggest function and uh let's get started i mean that's why i always covered the update function at the end because it can be confusing to people so that's why we have already seen delete book create book get booked by id and it will just have a combination of all of these functions right so let's create the update book function where u is capital and b is capital w http dot response writer comma r which will be http dot request right so i'll go till here no confusions so we have update book which is of models dot book pretty similar to our create book right the same same code we're writing out here details dot parse body so whatever you have sent in your request as the new body to be updated in the database for that same id that's what we're going to parse and we're going to take from json into a into a uh we're going to unmarshal it into a format that golang understands in the database understands so that's what we have done here now we want to get our id which is what is equal to mux dot vars so like i said so it's a mixture of the post the create book function and the get by id function right so book id let's go to vars and we get access to book id so till here uh we wrote some code from the create book function and here we have started writing some code from the get booked by id function right the same thing the same part we have to repeat here so id comma err i'm not going to copy and paste it because uh i always encourage you to write everything so that you get very very comfortable with the code right parse hint and book id comma 0 0 and if there is an error which is error not equal to nil then we're going to print out fmp dot print ln say error right right so completely the same till here right this this whole part is exactly the same and these two lines i just showed you is the same from create book so till now i think there's nothing confusing at all so now let's get the book by id right so we need to find that book if that book even exists in our database only then we'll update it right so let's find that book about details db equal to models dot get book by id and we'll pass capital id there if update book dot name is not equal to empty string it's not empty and book details start named okay so let me type all this out and then explain to you what all this means and if update book dot author is not equal to empty then book details dot author is equal to update book dot author right and then f update book dot publication is not equal to empty string then book details dot publication is equal to update book dot pub location so in our book model as you had seen there are three things right name author of application so when we have to create a new book right then while creating the new book uh you'll have to have these three fields name author and publication so we are assuming here in our controllers that the request that we'll get from the user it will have uh all these three properties name author and publication so we'll take the request that we got from the user inside update book and we have uh you know parsed it right so it should be utils dot yeah so this is a big mistake here that i've made it should be utilized parts body and not just parts make sure you update that as well right so let me check if everywhere else i have not made that anywhere else i've not made that same mistake yeah i have not so it's parts body little dot parts body and uh everything else looks to be all right okay so we are assuming that that update body after parsing has three things name author and publication so we found that uh body as we found that book from inside the database using get booked by id function because we have when whenever we pass whenever we call the update function we call we pass the id and we pass the body the new body for the new details which need to be you know set inside the database now so we'll have name author in publication and for book details right we need to start setting uh those three things so now book details is something that we get from our models get booked id so get booked by id by passing the id we get a book back in return and now we are setting the details for that particular book object right so we said book data's dot name now that will become equal to the new name that we have sent as part of the request that we had also passed right and the author will also now become equal to the author of the update book you know which is basically the request inside that we have passed an author so that will be become the new author and similarly the publication will also become the new publication so all of that detail is now inside the book details record which we now want to save in our database right so we since we have updated it now we want to just save it so updating is taking place inside our go link it's not taking place anywhere else so we just found it by id we now updated all the details and we're just going to go ahead and save it again right so dot save details now we want to send some response to our user as you know it has to be in json so we're going to send the book details which we just updated right so the updated things is going to go to the user so header and dot set content type comma pjq relation slash json then w dot write header http dot status okay and w dot write response so we've even sent the response to the user and so we have written our uh update function delete function create book get booked by id and get books so i think all of the work is complete so now let me just go between all my files and see so main.go file is complete config file is complete controller is complete models are complete routes are complete and utils are complete so all of this makes sense and now it's time to start testing and start fixing if we get any errors or bugs and also to check how to work with our of these apis in our post plan so let's head over to postman so we are back in our terminal because now we want to start trying to run that code that we have written the entire bookstore api so uh as you can see i'm inside my google bookstore folder right and it has cmd and package you can see that i want to go inside my cmd package and it has a main folder so i want to go inside my main folder this has that main.go file now main.go file is the file that we need to be able to run the go build command if you run the go build command anywhere else it won't run because it needs the main.go file now when you run go dot go uh space build i'm expecting to see a lot of errors right and uh you don't have to worry if you see the errors because that's a part and parcel of being a developer so you will have to uh you know get used to solving those errors that you get so as soon as i press go build it's going to give me some errors so right now it's giving me only one error but once i solve this error i know there will be many more errors right so right now it's saying that in book dot go file at line number 11 it cannot refer gordon dot model so i kind of know where the error is now i'm not going to edit all all of this out you're going to solve the errors with me so that you become better as a developer so you can uh you know identify so it's saying uh book.go file and at line number 11 is going to say gone dot model is not there so all i had to do was put a capital m here and now it won't give me the same error again or so i expect so if i say go build again it's giving me like i told you so this error is sorted but it has given me so many more errors right so the first error it's saying is it cannot refer to an exported name mux.vars so let's go head over to line number 47 in our go book controller line number 47 yeah so vars uh vars has to be capital v right so that's why it's not able to access so we'll say capital v and that error should at least go away right so this error will go away and then it says label book id defined and not used which is line number 64. so yes it's saying define but not used because i missed the is equal to sign here and i have a feeling that all of the other uh errors because they are much later into this same function so till line eighties here till nine number eighty from 65 to 80 i'm seeing all these errors and i have a feeling that they're all because of this is equal to sign that i've missed so now i'm going to go ahead and go build again and let's see if there are any more errors yeah so there are more errors it's saying uh go 71 3 undefined book details so let's find out so these errors are on line 71 74 77 and 79 and 80. let's look into the code what could be the issue here so 71 74 and all of these lines and the error basically saying that book details is not defined so i can see here that i've written books by mistake and not book details so once i fix that i remove that extra s hopefully these errors should go away and there could be new more errors no so there are no new errors when i ran go go build uh there were no new errors and it created this main file here for me and now i can start to uh run this code and i can start showing you uh from postman so you can say go run main dot go it it won't say anything that means that uh it's started running on your postman so now let's head over to our postman and i'll show you how to work with each of these apis that we i've opened up my postman window so postman is a tool that helps us to test all the apis if you don't know what postman is you can go ahead and watch any video from youtube and uh so what i'm going to do is i'm going to create a collection here and i'm going to call it bookstore my server is still running so inside my bookstore collection i have to create a request and i'll call it get all all right and then i have a request called create then i have get by id i'll have update and finally i'll have delete so for get all i need localhost 9010 where this project is running and slash book slash okay and if i get all i get an empty array and if this is what you get then your server is working perfectly fine you're getting the right result because right now we don't have any books so we get an empty array right and so that's why if we had don't have any books we have to create the book in the first place so we will create the book using the post uh or create right so we'll say book slash and then we'll use the post method we'll send somebody now remember in the body we have to send json and json will have three fields one is name the other is author and the third is make sure you get the spellings of author and name in publication right what is publication so name of the book is zero two one and author is peter thiel publication is penguin i think so you send it and you get a response which basically shows us that everything is fine and we get status 200 okay which we have only sent we wrote it right in the code that is that header status okay and let's create another book let's call it startup way by eric rice and i don't know what the name of the publication is so i've created two different books by the way both of these books are amazing if you're planning to start your own company i highly recommend you read these books and so you when we run the get all uh api again it works perfectly fine right we get both the books that are there in our database and now let's get by id so we have one book with id3 and we get that zero to one and one book with id4 and we get that as well perfect now we'll update the book by which which has the id4 and for the body i'm going to again select raw json and i'm going to simply copy and paste this here and let's change the publication to orion so it's updated the book and now the publication should have been oh sorry i have to read put here the publication will become orion right so don't forget to change the methods here right and for create the method was post and for update it is put right i hope that makes sense now we can go ahead and delete this book and for that i'll need the delete method in my postman when i send that you know the book is gone hopefully so now there's only one book remain which is which has an id3 which is basically zero to one by beta theta so all our five apis working perfectly fine and if you have completed this video and you have been able to uh code out till this far uh congratulations in this video we're building something very interesting we're building a slack bot that calculates age uh using golang without any delays let's get started so uh the prerequisites to this video are that you should have a slack account right obviously that's how you'll build a slack bot right so you should have a slack account you should have a workspace in your slack and you should be the admin of that workspace only then uh you'll be able to build a bot right in slack and then you have to come to this link api.slack.com apps and this is where we'll be able to start our apps so i'll say create new app and ask me two different questions from scratch or from an app manifest so in this case i'll be building and building a bot from scratch i'll call it the agebot right and i'll give it my workspace and now uh we have to find socket mode on the left is the third button on the left right socket mode and we have to enable it and we'll call it socket token so this will generate an app token for us x app so when it says xapp it is your app token and it says xob it's your bot token right x2 xb it'll be your bot token so you can make a note of this you can copy this i won't copy it right now i'll come back for it later on in the video uh so this is your that was your app token and now let's go for our uh event subscriptions which is the third uh button so the fourth button from the from the last right and we have to enable our event subscriptions we have to subscribe to what events and uh let's add some events right so events are basically uh that or something that our bot uh would be subscribed to so these are socket events so i'll say app mentioned whenever somebody mentions my bot and i'll say message history and i'll say message.im right it can read messages and then messages.channel messages.mpim right so these are the uh events that i think my bot uh would need to be subscribed to uh but then there's always you can always come back and tweak them later on if you by mistake if you leave out any and you can always uh you know this is mostly uh you'll get these by trial and error right so i've built more than 50 slack bots so i know and and this is a tip for you as well that it's always better to add more events than less because and and also now uh what we'll do is we'll add uh oauths and permissions so come to this uh option above event subscriptions so oauth and permissions also you have to add some uh permissions like scopes to your uh bot uh these are very similar to your event subscriptions so here also it's always recommended uh with even subscription and with uh oauth information it's recommended that you add more than you need because uh most of the errors that you'll face when building slack bots would be around uh your bot not having enough permissions or authorizations or authentication you know those will be the kind of errors that you'll face so it's better to always uh you know add these so that you don't have to like deal with a lot of errors right later on so i'll just add some regarding chat right and uh let's say channels read right and then say um i am read and i am right these are the items are basically direct messages mp i am read and npm right also i'll add right and i don't think i need any more um permissions for now but if i have any errors then i'll come back here and i'll add those permissions right and now the problem with building slack boxes sometimes they that you don't even get an error and your ad you're uh you know doesn't respond properly or and it doesn't give you the behavior that you're expecting it to give you and and those problems are mostly revolving around scopes right so there are so many errors on stack overflow when you go and you won't find answers to those problems because uh those most of them are around scopes those aren't even errors like people would be saying my slack bot isn't working and those kind of issues right so those are all around scopes i can tell you that from experience anyhow what we'll do now is we'll actually click on install this to workspace and it'll ask me for some permissions i'll say allow so that means now age bot is uh installed to my workspace and it has given me a bot user oauth token right so i need to make a copy of this as well uh so now what we'll do is since we have our credentials in place now it's time to actually start uh building the bot in golang right so i'm in my uh directory where i keep most of my golan code and i'm going to create a directory for this particular project called slack age bot sorry for the wrong spelling of age and i'm going to go inside directory and here what i'm going to say is i'm going to go mod init github dot com slash uphill slash slack i'll say um slack age bot is the name of the project so this is an absolute link that helps me to import other files in my project and in this project particular project we don't have multiple files we are going to only get to have the main.go file but if this was a bigger project then this would have been very very uh helpful and also using github.com uh you know helps helps a lot because later on if you have to push this to github and then use it as a package in your own project later on or somebody else has to use it as a package in their project it's very very useful so this is the best practice uh you can always innit your go programs like this so we'll init and it is taking some time i don't know why okay that's done and there is one uh external package that we need so i have to run the go get command and the package that i need is github.com shoma lee one one slash slacker all right and uh just to be sure i'll say go mod tidy okay and so we have added the the package that you want so if we ls right now we'll see our go modern go some file which is perfect which is exactly what you want so now what we'll do is we'll open up our code editor which is uh vs code in our case in my case uh you can have any other code editor that you want but vs code works best for me so i'm going to use obvious code and now we'll start writing our code as you know uh the main file in a go program is called main.go and the first thing that you have to write is package main then you have to import some packages i know that i'll be needing the context package i know i'll be needing fmt to print out stuff and log is something that i'll be needing i'll be needing os package and the most important thing that i'll be needing is the external package that i installed right so i'll say show molly11 now if you're uh yeah so if you're uh coming from a javascript background so what i did there with goget command is simply uh you know uh npm installer it's it's exactly equivalent so it creates uh those entries in your go modern go some file which is almost like your if you're from a flutter background it's almost like a pub spec yaml file or popsicle dot log file and if you're from a uh node.js background it's from it's like a uh you know package.json and package.json.log files you know that's what these are it's very very similar concept right and uh so what we're doing here is we are going to uh write our main function funk main and in funk main i'm going to set my environments right so i'll say uh now you can you know set your environment in an env file but i'm not going to do that i'm just going to uh you know use my os uh package to actually set environments and i'll say slack bot token okay comma and here i need to copy and paste my slack bot token and then i'll say set environment slack app token right so far so good and now what i'll do is i'll just uh go ahead and get my tokens from the slack uh this is my bot token so i'll copy this and i'll paste it here this is my what token all right and here is my yeah i'll and to find my main token i have to come here this is the socket token that we created that is our the xapp one that is our main app token so i'll say i'll copy and paste that here as well so far so good and now we have to create a bot right so we'll say bought an assignment operator or the walrus operator whatever you want to call it slacker dot new client and we'll say os dot get paid environment this is slack port token and we will say comma os dot get environment slack app tool now uh you don't have to have uh you know set environment get environment you can directly pass the tokens here directly right inside the new client uh function but why i'm doing this is because this makes your program more extensible so later on when you have to extend your program and uh you you have those environment files or you have a production environment where you have these tokens or you're using some program that manages all your credentials then this comes in very handy so i'm just getting you in the habit of you know going the right way from the beginning so here we'll start to go routine which will uh it doesn't do any much it just prints uh command events so we'll say command events by command events i mean uh the e like let's say whenever i pass a command to my slack bot uh so whatever it does or whatever the the way it handles the event at the event itself it's going to print it out right so this means that print command events needs to be a function which we have not created right now so let's create that function so we'll say func print command events and we'll say analytics channel and chan creates a channel and we'll say slacker dot command event which basically we're passing here right and here we'll say for event we're going to arrange over the analytics event analysis channel and we're going to print out a couple of things so we're going to print out the timestamp as in when the command was received by slack right and the command itself and the parameters that we have passed to that command and the event right so let's get started so we'll say print ln and here i'll say command events and then i'll say fmt dot println and i'll say event dot timestamp like i said we need the timestamp fmp dot rent ln event dot command and fmt dot print ln by the way all of this is uh totally optional you don't have to do all this like i'm printing out uh in my console whenever any event takes place uh in my program but you don't have to do this given dot event and then just an empty line we'll put them into line print ln okay so far so good now comes the real uh function the most important function but before that we need to write some code to actually stop our bot cdx cancel context start with cancel and context dot background if you're a golang beginner i'm sure you already know what context does and what differ is differ basically make sure that uh the cancel uh is you know uh all like played or or this function is called towards the end like when this function is about to end right so that's what therefore does and error is equal to bot.listen your bottle listen to the context if there is an error which means if error is not equal to null you're going to log out the fatal log.fatal fatal is a function that logs out the error so we have used our log package that we had here we've used our os package to set the environments we've used our fnd package to print out stuff and all we need to do now is use the slacker package right uh now let's create the program that we need to create so that program is bot.com so we have the what we've created the bot here right and here we need to say bot dot command so this is where the magic is happening my year of birth is and you pass a parameter inside here so this with these two uh angular brackets is the parameter and you'll say ampersand slacker dot command definition and this is the description of the command so we'll say you know iob calculator and just give an example sorry example my is here 2020 all right so this is an example and then we give it a handler so handler is where we handle this uh event using a function which takes the bot context slacker dot dot context and we pass it the request so as if whenever we have any functions that uh you know work with http kind of data or socket data you know you have to have request and response right and request will be slacker dot request and response will be slacker which is the package again dot response writer so uh slacker dot request lack of dos is responsible we are using the slacker package here all right so everything makes sense till now i hope everything makes sense to know it's giving us one error i don't know where the error is but anyhow so let's create this error so we'll say here is equal to request dot param here so whatever here has been passed so when the user says my yob is here this uh param uh we'll get into a variable call here right now using this and then we'll have a variable called yob so we'll say string convert dot ato i here we'll convert into here so now this means that i need another package called string convert because this is not native to golang this is a this is a package in the golang library right so we have to get string convert as well uh so uh so far so good so we have our here in yob and then if error not equal to nil we'll say print ln error okay and then we'll say age not equal to sorry a is equal to 2 0 2 1 minus y to calculate h all you have to do is year of birth has to be subtracted from the current here that's going on right now it's 2021. if you didn't do this right if you don't use string convert and atoi function you would have this uh in a string format and you won't be able to subtract it here golang won't allow it so to have a number of took uh to get a number from string you have to do this and only then you can perform a subtraction operation right because golang is a statically typed uh language you can't subtract a string and a sprinter and an end so we'll say sprint f which formats our string for us age is percentage d comma h we'll say response dot reply r so in age we store 21 minus yob which is the edge and then we format it out like this with this text and then we reply this now i'm getting two errors one is this so we don't have this package it's saying somali double one we should have had it because we added it um i did add it actually so let me say again go get github.com slash somali one one slash slacker it says it has added this package then i don't know why my uh vs code is acting up and then uh it doesn't seem to have any more errors this is the only error that says uh there is there could be an issue with the spelling though i mean uh now there's no squiggly line so everything seems to be all right um and then it's giving me a red squiggly line out here i don't know why let me check so it says bought command okay yes so my mistake uh this function definition we can't close it out here this needs to be closed somewhere out here and here there needs to be comma now uh there shouldn't be an error now and yes spelling of command events is wrong so i've collected that as well now it's a question about of i think counting these brackets so i'm just going through it again i have written the description i have the command line the description and there's the example there's the handler func uh request response then i have the year then i have iob uh print line age 21 sprint f response reply everything seems to be all right to me but uh it seems there's still one error right so it says in the even dot parameters there's an issue yeah that's because the spelling of parameters is wrong and now as you can see we don't have any issues i'm using a golang plugin that helps me to find these errors without actually running the code so which is very helpful now what we'll do is we'll say go build to see if there are any errors there there seem to be no errors it has created the dot apc file for us and uh what we'll do now is we'll head over to our uh slack channel and here we will uh be expecting our bot once uh we start the bot right we start the program and so let's do that let's actually start our program so go run main.go so it says connected to slack with socket mode that means everything should be fine and so here i'll say agebot and i'll say agebot my yob is 1990. so it says the slackward says that you mentioned each board but they're not in this channel so i'll say invite them and then uh agebot automatically replies age 31 awesome right so you'll say age bot my y o b is 1995 let's say age 26 isn't that awesome so i hope you learned a lot in this video and uh you were able to uh you know understand how to actually apply your golang skills and how to build a slack bot right and how to get the tokens from slack how to add those permissions and how to enable socket mode all of those things are really important in building a slack watch and also this kind of function and the package that we've used slacker right that makes making a slack bot really easy in this video we're building something very interesting we're building a slack bot that can upload files on a slack channel right so the prerequisites are that you need to have a slack account obviously and you need to be the admin of a workspace basically on slack and then you have to come to api.slack.com apps now if you have built slack bots before and you just want to know about how to upload files then you can skip the part where you know i'll show on how to uh get your bot token and your app token and you can skip directly to the part where uh we start working with golank or otherwise you can stick around and see how we need the we can get the bottom right so uh we're on api.com apps we'll create new app from scratch i'll call it filebot and the workspace is worldtech create now i need socket to be enabled so i'll click on socket mode the third option i'll enable it and i'll call this token the socket token generate so let's generate a token for me and i don't need this token for this video i just need the uh what token in this video so what we'll do now is we'll actually go to even subscriptions and we'll just enable it as well even though we won't be using events in this video but we'll just enable it anyways and then we'll go to our oauth and permissions all right so let's give it some scopes so obviously we need to be able to uh read messages so let's i'll just say chat write and channels read and then i need files read and files right and i'll also say i am reading i am right now uh if you've watched my other videos on how to build slack bots the other videos then you know that i always recommend going for more scopes than you need because a lot of the errors on slack stack overflow around slack bots have been caused because because of authorization authentication and permissions issues right and they all revolve around the scopes so it's always uh good to have more scopes than you think you would need because sometimes the slack bots don't even give you errors so that can be very frustrating sometimes right so we'll have remote files read and remote files share and write also i'll take those as well so remote files sorry not remind us right but remote files the remote files right and share okay now most of these we may not even use but we are still like i said you know you're still keeping them so we have all these uh scopes and it might so happen that we uh you know um we might need to add more uh depending on if our bot is able to perform the actions that we're expecting it to uh perform so it's asking me for some permissions i'll allow it okay and now you have your slack watercolor i won't copy it right now but i'll come back for it all right and uh the other thing that you would need is your slack channel id on which you would interact with your file bot and i'll show you that as well all right so now what we'll do is we'll head over to our powershell or uh you could be on your mac terminal or ubuntu terminal doesn't matter the commands will be the same all right so i'm in the in the folder where i keep most of my column code and what i'll do here is i'll create a directory called slack file port all right and i'll cd into slack file bot and i'll go mod in it and slap file what this is my absolute link if you if you're very new to golang this is your absolute link with the help of which you'll be able to uh refer refer other files in your project in this project particular project we are going to have only one file main.go but if this was a much larger project uh then we would have to uh you know write multiple files and github.com because once you upload your project to github you might want to use it as a package in your other projects right so it's always a good practice to have your absolute link like set up like this so this is a good practice we'll go mod in it and it has created a go mod file so if ls you'll be able to see your go mod file right and then uh you need a an external package to be able to work with slack so we are going to import that now if you're from a javascript background you would recognize this as your npm in it and you would recognize this as your npm install so don't we are just installing an external package so we will call it github.com right so this person uh just like us this person had given github.com link so that you know now we are able to access his library very easily into our project so we will get that so it has hopefully added the slack go slash package and what we'll do is just to be sure we'll also run go mod id and says all match no packages no issues everything works perfectly and now what we'll do is we'll open up our code editor so i'm using this code you could be using any other collateral no problem and just another pointer i'm also using a golang plugin in my vs code that helps me write better code so i'll leave the name of that in the description box below but even if you just search for extensions uh golang extension you'll find it it's not it's not something very rare everybody uses it so we are in our vs code and i've opened up a file called main.go which is uh what the main file in golang program is called in case you're new to golan the first thing that you write in a golang program is package main and then you import some libraries and then you have something called respond right so these are the things that are uh the most important in a golang program and uh i know that i'll be needing fmp to print out stuff so the format package has uh things that are required to print out stuff to the terminal then i know i need the os package to set and get my environments and i know that i need the external package that i just installed called slackgo to help me talk to the slack apis right now slack go is a rapid library that somebody has written around the slack apis in golang so that we can call uh the funk the golang the slack apis as functions rather than as actual api so we don't have to make network requests to the slack api because somebody has already written wrapper functions around it and we just have to call those functions uh using this library right so that makes our job extremely easy and then you can uh create a variable called api and it will have slack dot name so using this package now slack and we're creating a new connection we are calling it and here we will get uh you know uh something from our environment and it will basically be our slack token now uh ideally you would have an environment file right or if you're in production environment you would have uh that those the environment set up to have these variables but since we don't have it set up what we'll do is we'll actually set our environment right now using the set env you don't have to do it you can directly pass your bot token here but i do this because this makes the code uh very extensible and you can extend it later on if you in case you want to go to production uh like i said we don't want to go to production right now but if you wanted to you could because we're keeping everything uh modular right so uh here we'll put at what token and also one more thing that i need uh like i said is the channel id on which uh the bot will be able to uh write the upload the file okay so here i'll have something called as channel uh and this will be my channel basically it's also string and os dot get environment inside that we'll have our channel id all right and then i'll have my file file arr string and here i'll put the name of my file you know whatever i wanted to be so now let's go back to our uh google chrome and get our slack bot token and channel ids so slack bot tokens this is my bot token so i'll copy it and i'll paste it here okay and now we'll have our channel id and i need to get to my channel id so this i wanted to post it out also on the general channel so i'll say i'll right click on the general channels i'll say open channel details then towards the end you'll find the channel id which is this okay and then i'll go back here and i'll paste it here makes sense so now we have set our environment for our slack buttock and slack and channel id and we uh sorry yeah and then we have our uh you know uh variables api channel and file which have the api connection with slack and then uh the channel and then the file that will be sending out uploading basically and now we'll create a for loop so uh right now we have only we'll have only one file here but we could have multiple files right so we have to uh go over all of the files that exist in this variable in the slice right so in the slice all the files that are there we'll say i plus plus and say programs slack dot file upload parameters so this is a function that slack gives us and it will have two parameters okay and we'll take that into of our own variable called params so the two parameters are channels where i'll pass the channel in which i want to upload the file and i'll pass the file itself which will in this case be file a r i right because we are looping over file arr which uh in the for the sake of this video will have only one file but you could have multiple file here files here like hundreds of files and then you could loop over them and then you could uh you know send them here all right so put a comma here because it's giving me some formatting errors so i'll say api dot upload file with the params all right so i have my param set here with channel and file and i'm going to call the function called upload file uh in my connection the slack api right and i'm going to uh take that into a variable called file or it's going to return an error to me and so i'll check for the error so if error is not equal to nil that means there is an error i'll print it print out fmt dot printf i'll say percentage s new line comma error all right and we'll save it on and then we'll print out the name and url of the file so let's say name percentage s url percentage s new line so this is a very short simple program and even though i've added slack i don't know why it's giving me shoes i don't know why there's a squiggly line and shows one error even though i had actually got my import the package so this sounds this looks a bit off to me uh but yeah everything else in the program looks okay to me where uh let me just go through it again so that uh you know we're able to minimize uh the errors so there's the channel id and slack dot new slack oh yeah so here we have to just uh pass the file so you can copy any file that you want and i'm going to just copy and paste a file called zipl uh dot pdf all right so i'm going to pass here is that apple.pdf but you could have any file out there and after that everything else looks pretty all right to me so i don't know why there's a squiggly line here even though i've installed the package what i'll do is i'll again run go get github accounts like slash slack so i'll again add it and now hopefully the error should go i'm not sure yeah now it's gone weird right anyways so let's uh run our code let's build our code at least to see if there are any errors in runtime there are no errors so we will say go run main dot go and at the same time we have to keep our slack channel open right so here in the general channel is where i'm expecting the file to come up right so i'll say go run main dot co and let me head over to my slack channel and see if the file comes here i don't see the file yet says not in channel so this looks like an error to me uh and i'm pretty sure it has something to do with the permission so let me uh go over to my uh slack terminal and slack dashboard and see what these so back in my slack dashboard or my channel i think the issue could be that the file bot is not part of the channel right so what i'll do is i'll try mentioning filebot and so it says want to add this question instead isn't in general yet so i'll say add to channel so file bot was added by kil sharma and now what we'll do is we'll run our code again and see what happens and let's go back see it was able to add the file it was able to upload the file so it works perfectly so you'll have to add your file bot to the channel before it can start pushing files to this channel right and if you see this error it's not very helpful right so it's not in channel i mean what the hell does that mean and i've uh you know had so many errors in the past like i've built more than 50 slack bots like are there on production on you can get them on the app store at the slack app store uh marketplace and then uh the thing is it's so frustrating to build a slackbot because most of the time the errors are around like i told you the scopes right and uh because you're trying to do something and you don't have that particular scope selected and then it won't even give you the right error it'll just say uh you don't have uh the authorization or you don't have the permission something like that but it won't tell you uh what permission you don't have so it can get really confusing so just make sure you add more scopes than you need and whatever scopes you think you might need you can obviously add them and don't be shy and just add as many scopes as possible just add all of them probably you know it's not like you're going to share your tokens with anybody else right uh like delete so for example i just made this uh test uh uh app i'll just delete this uh what after uh the video is over and uh now if you're going to into production obviously if you're launching a slack bot to the marketplace then obviously you need to think about what are the exact scopes that you need and you can remove the ones that you don't need to make it more secure but otherwise while testing it while learning go ahead and do whatever you want right in this video we're doing something really interesting we are building an email verifier tool so if you search for email verifier tool on google you get all these different options right hunter dot io snow dot io zero bounce never bounce and all these tools like let's say if you open up snow bio and if you open up email address verifier all these tools are quite expensive and some of some of them even say that well didn't check in real time right uh they try to sound really fancy but what's happening here is really straightforward it's there's nothing fancy happening there only in some tools like let's say um hunter dot io they use a little bit of machine learning here and there to uh you know determine uh basically to make the tool even better and more enhanced but otherwise most of them are just using very simple uh tools to uh create an email verify tool so if you wanted to you could uh simply take this program that we'll build right now and you can just launch your own email wi-fi tool if you want to i mean completely optional all right so we'll use golang nothing fancy we won't have bulk uh verification um ability right now in this program it's very simple you can extend this the functionality of this program to include bulk uh checking as well and in the future uh a few weeks from now i'll actually build a complete uh you know like a complete solution for email verification all right so this is just a precursor this is a very simple program that you're building right now but a few weeks from now i'll build a complete project around it all right where you can uh also do bulk checking and you know there'll be a more there'll be a few more checks right now we're doing a couple of checks but there will be few more checks all right so let me show you how the program is going to work i am now in my terminal and what i'll do is i'll start the program and mind you this program is super simple so it won't take us more than 20 25 minutes to actually build this whole thing right it's very very straightforward so if you go down main.go it shows you these options it says that when you uh enter a domain name right now it will give you the domain names name and will check for mx records spf records if it has any fcf records if it does then we'll give you the spf records if it has any demarc records and we'll give you the democratic calls all right and by checking these then we'll know uh if the domain is at least right from which that email id is come out from to which you have to send the emails to right you'll just check the domain if the it even has any imax records so that's like the first stage the first check of any email looking up or any email verification that checking if that domain name even has an mx recorder an spf record as a democrat record right so that you can know at least you know there are mx servers set up there a mail server set up there all right so uh here let's say you write mailchimp dot com so this is like uh irony because these guys uh help people send emails and we are building a tool using their website to check if they have any valid uh you know email records so let's enter that it'll take a while because mailchimp has done a lot of clever things to uh you know not respond straight in a straightforward manner so i'll say that uh the request has timed out right it says uh this operation returned because the timeout period expired but it'll give you still give you the right records it'll give you mailchimp.com which is the domain does it have a mx record that says yes true it does does it have spf records false so that means spf records uh there's you can see this there's a blank here that means uh since there's no spf records it won't return the spf records obviously does it have dmarc it'll say true and demarcus records this these are the mark records all right so now you know that mailchimp.com is a valid email people it's like emails have been set up on this record and now you can start looking for the names of the people and then actually finding email addresses of those people if you wanted to right like i said a few weeks down the line we'll build the entire product right now we're just building like uh you know just telling people if the the email is real or not just like something like uh you know this this tool out here called email hippo you write something like you know akil at the rate mailchimp.com and the first thing is going to check is what we just checked right now does it have mx records uh spf records or dmacc records if it doesn't we'll just say that this email address is not valid obviously because the domain itself is not valid right the one itself does not have any mx record setup but here in this case it'll say true because in our case also it returned true so i'm not sure if this is yeah so it's saying the result is bad because yes the email address does not exist but uh probably it's saying that this exists but this email on this this person on this domain does not exist something like that right so anyways so you get the picture of what we're building and now let's start building it like i said there's no external library used here we're just using like the basic golang packages that you get so if you know even basic golang if you just completed the golang tour if even if you don't know that actually uh you can you can still complete this project so this is like a you know simple uh like a beginner level project so feel free to follow along with me all right now since this is a beginner level project i won't explain a lot of things there's not much to explain anyways i won't explain a lot of things uh feel free to code along with me if you don't understand anything look it up on the internet or put it in the comments below i'm always there to help you out right but it'll be really simple right so it's i mean there's nothing complicated here we're not using go routines we're not using channels we're not using even structs we're not using uh interfaces nothing like that it's just like plain simple colang all right so let's get started what i now want you to do is open up your new terminal and traverse to the path where you usually keep your golang code and create a new directory let's say like email checker tool cd into it and open up using your favorite code editor in my case it's vs code and here there's not much in this project right it's just main.go so you'll start with package main you'll import some things obviously we'll talk about them in a while and then there's yours there's your uh funk main right the most important function in any golang program funk main basically calls another program called funk check domain all right and this function just takes in a domain so essentially all you're entering uh that you just saw in the demo or you're entering is the domain name right so that domain name basically gets passed passed from our uh terminal using funk main something we'll write in our funk main we'll pass it and we'll just push it or send it to our check domain function which will do all the magic all right the packages that i need here i need buffalo the buffer package to to be able to parse whatever i put in the terminal i need fmt to print out stuff log as well need a net package to make those requests os and strings once we use these packages it will make more sense to you why we're using it so firstly you'll create a variable called scanner and you'll use the buffer package and there's a function called new scanner that you'll use okay and here you'll say printf and the things that we're printing out when the program started will be basically domain has mx has spf and if it has spf then it'll show you the spf records then we'll check it has the mark and then we'll check for the mark record okay so if you remember when we started the program it just showed us these things so that we come to know in the order which will in which the information will be shown to us okay so it's exactly the same thing and now for you to scan the information you'll use scanner.scan function and you'll so let's say there are multiple items to be scanned you'll now i i know i said that there's no no bulk uploading uh as in bulk checking but you can check like a few uh you know emails but when i say bulk uh checking i mean like like uploading big csvs of thousands of records and then checking them in one go right that's what we don't have but like multiple checking is there all right i hope that makes sense so you have scanner dot text so uh whatever was typed by you in the power shell or in the terminal is now basically sent to the check domain function one by one so multiple domains if you know if you want to or it's just a single domain mostly i have tested only on single domain so please um if you know there's a there are problems working with multiple domains then uh you know it's only because i've not tested it i've just associated with a single single domain so start the program and just put a single domain like mailchimp.com like i showed you in the demo so it just works perfectly fine for that i've tested only for that and then we have like i said this is not a production level software right i said like you can put it on your website as a small simple free email checker tool but don't like charge people for it because you don't have uh the complete architecture required for it to be a complete production software right i hope that's clear because i i get strange uh comments sometimes so that's why i just you know clarify all these things so to um log out the error now if there's an error obviously uh then we're just logging out the error so the error is could not read from input comma error so if you notice all that we have done in the funk main is just pick up or scan the user's input from the terminal all right the domain name that you've put and if it's not able to scan it properly whatever domain name that you put is going to say could not read from input right it's going to print out an error and what we are sending to this check domain function is the text and that whatever you've posted in the terminal and now the check domain is the is the part where which is basically the meat of this entire program because this function will have all the logic required to actually check those records okay so firstly we'll define some variables the first variable will be has mx has spf has d mark all of these are boolean then we'll have the spf record i mean if it has an spf record then we'll show the spf record right like in our case when we uh did a demo with mailchimp there was uh this was false so that's why we didn't have any spf record it was blank and if there's an uh dmark tool like we had did for mailchimp we had democtool we'll have remark record here and it'll be a string all right now we'll all be doing here basically is using the net package to firstly look up the mx so the net package already gives you um the ability to look up the mx of the domain that you just sent here domain is that string that you're passing to this function all right and whatever comes back from this function we captured in a variable called mx records and this function if there's anything that goes wrong will also return an error and now you're getting these quickly lines because you've defined all these variables but you've not used it right so what we'll do now is we'll say if error not equal to nil this error basically will handle on this line log dot printf error percentage v comma error and we will check for length and extra chords greater than zero is equal to so you looked up the mx for the domain using the net package and there's a function called lookup mx that you get in that net package and you got the mx records or optionally you must have got the error so if you got the error which means error not equal to net you'll just print out the error and if you got back the mx records then you'll check if the length of the mx records is greater than zero if obviously if it's greater than zero that means that mx that this domain has mx records so we'll set mx is equal to true has mx is equal to true okay so this has been used now comes the txt records which are your spf records okay so we'll use net dot lookup txt package so here um i just want i wanted to observe how easy these kind of things are with a language like golang if you want to do the same with uh node.js for example you will have to use an external npm right something like that um i mean i'm a node.js user i've been using it since many many years now i have uh built multiple products with node.js so um i should have nothing against node.js but actually i do so i do have a lot of cloud against node.js because to do something as simple as this you have to uh you know do a lot you have to do a lot of bending uh in case you know a better way to do this with node.js do reply in the comments and to share it with me i don't know but with golang it's super simple right you don't have to install any external package there's all these are you know the standard golang packages that you're using right now and that's insane right a language that has so much support out of the box it's just killer this is that's why you know it's the language i use the most right now uh so here also you look up the texture codes which are basically your spf records right so if uh similarly you'll check for the error so if you say you'll say if error not equal to nil then you'll do something here so you'll say log dot printf error percentage v slash and comma error and then what you'll do is you'll you'll range over these records so range by by ranging over if you're very new to golang i basically mean like using a for loop to go over all the values okay so we'll go over the text records and the right syntax for that is for and records so this is going to be your iterator and this is going to be your uh every single value that you'll have access to with the help of range records so inside your text records you'll range over them and every single value inside that text records you'll have access to it using this variable called record and here you could have used the iterator like i or j or something like that but since we don't want to use it we put a blank character here because in golang you can't just define something and then not use it okay that's why you have to use blank characters so here we'll use the strings package provided by golang again by default and you'll use the record record is basically every single value like i told you from this text records once you range over it every single value can be accessed using record so we're passing strings.hash prefix in that function we're passing uh the record and we're checking if this uh it has been represented like this so usually the spf records in your text records right all your txt records and that you want to find or search the spf one records okay if the way they represented so if you go to your let's say your godaddy or your name cheap you'll see that you'll you have these dxj records and they will look like this they'll have like a v is equal to spf one and so you'll obviously set the spf has spf is equal to true and then you'll also have your spf record which will be set equal to the record now and then you'll just break away from this program so a few minutes into the program we have already checked for the mx records and spf records all we now need to check for are the dmacc records now to check for the democracy calls we will again use the net dot look up txt but we'll check for dmarc plus the domain domain again is that same variable that was passed into this function and here we'll say dmarc records comma error so whatever is coming back from this function the function is lookup text that you have already used in the net package you're passing domain plus the dmac record to check if you know you're looking up the remark records using the same function and whatever you're getting back you're either getting an error or you're getting the dmac records so we'll check for the error so if error not equal to nil say log dot printf and we'll print out the error and otherwise we'll range over the dmacc records to do that you have to follow the same kind of a syntax and here you start to say if strings dot has prefix record comma v is equal to d mark one so you're doing you're following the same uh method process there's no change here all right same process and here instead of record spf 1 we're saying dmacc one and if it does then we'll say has the mark has become equal to 2 true and dmarc record value is equal to the record value and then you break away and at the end you'll just print out all the results right so you have to use the printf method and to print out the values so you'll say um i'll put the percentages later on percentage vs later on the values that i want to print out to the terminal our domain has mx has spf i have this reference right domain has a mix has this we have all these this was just text and here we're actually pushing out like printing out those values but in the same order spf record comma has daymark comma d mark record so how many v's do we have to put here one two three four five six so let's say percentage v comma percentage v comma percentage v comma delta v comma percentage v so it's five now and then the last one is six six percentage v and this whole function is complete now all we have to do is test this function and we know that we'll get some errors and then we have to solve those other errors and everything will work to actually find the errors and see if it's working we'll have to actually run it on our terminal so here i'll say go run main.go and as you can see it's working so i'm surprised that there are no errors it's working everything's working fine let's try entering mailchimp.com again i've tried it with many of the websites like mailchimp and sendgrid send in blue all of those main big uh email sending tools you can try more um domain here actually any domain you try you can try it here so this as you know the request will time out after a while and then we'll get those results and if it doesn't give you any results then that means there's some error with our program but i'm hoping it'll give some output yeah so we have got that output that timeout be expired and then you know you get your dot com true false true and you get the d marked records okay so i hope you enjoyed this program uh this project this is a very small simple project but you know obviously it's a nice flex you can flex in front of your friends you built like an email verifier tool all right in this video we're building a very simple aws lambda function using golang so aws lambda is a serverless technology where basically you create functions and you host them on the cloud and you only pay for usage so whenever only somebody uses your functions only then you pay for them so there are a lot of use cases for serverless it's a growing technology everybody's uh shifting their stacks and hashtags to serverless these days and uh it's a very i found it to be a very good fit for let's say if you're building an mvp because you don't know if there will be traffic coming to that product right it's not a proven product so you don't know if there's any traffic that's going to come to it so that kind of uh you know um at least ensures that you don't have to keep paying for your servers right you only pay when somebody uses your product um and a lot of people use it throughout the development life cycle like they uh throughout the product cycle life cycle right like uh right from uh the pro poc to the mvp to actually scaling because the scaling uh in serverless uh using lambdas is very easy because you actually don't have to uh write any like huge configs right you don't have to create servers everything is done automatically for you on the cloud uh so it's a completely managed fully managed service you don't have to do a lot basically right so you just have to focus on the business logic which is just creating your functions and everything else is taken care of by the cloud it's also very cheap to use because you're not paying for the servers right you're only paying when somebody uses your programs or functions so if you're building an api that's going to be you know exposed to the world and the world is going to and there are many more developers who are using your api then aws lambda is again a very good use case for that now there are a few drawbacks to using aws lambda for example uh there's cold start wherein you know if you're if somebody's using your lambda and basically the lambda takes a while to start so that's called as a cold start because there's a slight delay there sometimes uh so they've tried to reduce it but it's still there i feel uh cold start problem is still there so so drawbacks will always be there but it's a it's a very good technology everybody's kind of adopting it everybody's using it it's widely used very popular it's important right so it's important to learn and so that's why i wanted to create this video uh which is the basic uh creating a very basic co-lang function and then deploying it as a lambda function in aws now uh you will find a lot of videos where people use the gui the aws gui to deploy a lambda function but in in my case in this case i'll be using aws cli because i did not find many uh tutorials actually i didn't find any tutorial on youtube which uses aws cli to deploy uh golang lambda function all right so that's why i thought let me create one because i don't use uh the aws gui a lot i use the aws cli all right so now there are two prerequisites to this video one is that you should know the very basics of golang and actually even if you don't know the very basics of golang i'll explain line by line the whole program to you it's a very small program so that's probably not a big prerequisite the second one is important second one is that you should have aws cli installed and configured on your laptop or on your whatever desktop machine whatever that you're using right so that's that's kind of important you need to have aw cli installed because like i said you know i'll be showing you the aws cli approach not the aws gui approach because that's something that many people have covered already right aws cli i find it to be quicker faster and uh you don't have to like leave your window and if you're a nerd like me like obviously you like working on your terminal you don't want to use gui right now for uh now the next video that i'll create after this will be a complete serverless stack that will be creating right we will create apis that can be exposed to the public and those we'll create using lambda dynamodb and api gateway that's a complete serverless stack that's in the video that's coming up soon in that case since i don't want to create very complex config files i'll use the aws gui to deploy the lambda functions and to actually configure my api gateway um but only because the config files are going to be very very complex like yaml files so that's why i want to do it on the gui and not from and not write those yaml files so that's why uh here because uh it's kind of easy i'll just use my cli all right i hope that makes sense and even in the upcoming video i'll create uh config files if you want me to i'll show you how to do that but i kind of prefer going the gui route in a project that's a little more complicated all right that's just my personal preference so having said that let's get we'll have to get started now a lot of talking has happened so this is my terminal and uh you don't you don't necessarily need to um keep the project in a folder where your golang is installed right like go path and go route could be somewhere else you can have the project anywhere else doesn't matter because we'll be using the uh like like we always do right the golang 1.12 uh the the format that came after golang 1.12 which was basically uh you know using co mod in it right which can initialize your go mod file anywhere it doesn't have to be in the root or path so but uh usually also i i prefer keeping it in the go root and go path because i've been a golang developer for a very long time so that's why i prefer keeping it there but you can keep it anywhere right so because i'm i'm saying this because i get a lot of questions on youtube saying that hey my go path is you know configured like this where i'm keeping my project like this is that okay and do i need to keep my project in guru so the answer to that is you don't have to do all of that you can you know keep it anywhere i i keep my projects in the go root most of the times because that's how i've been doing it since very long time before even before golang 1.12 was there right so you don't have to do it i mean um you know the go modern it takes care of everything you don't have to do anything so let's create a new directory so we'll say lambda yt example okay and so we'll cd into it lambda yt example and here we'll just say go mod in it and to initialize i'll say github.com slash akil slash um go lambda function lambda function three okay because i've created many lambda functions on my aws account so i just need to be sure that this is a different lambda function all together all right now this is my project file project name and i don't have to keep the same name as my lambda function that i declare in my aws but i'm just for consistency's sake and that's what i'm going to do i'm going to have this name the same exact name in my aws uh lambda console as well when i declare the function all right uh so there are two parts to this video uh as in the video will be one but then i'm dividing it in two parts like contextually the first part where i'll be building the golang function with you which will be a simple function and the second part where we'll deploy that we'll we'll do the aws configuration parts the second part is slightly uh where you need to pay more attention uh because that's where all the magic happens and the first part is just creating the golang file so if you want to go quickly through the first part no problem uh you know just make sure that you slow down in the second part where i actually show you how to deploy uh the golang functions because there are a lot of caveats there a lot of different you know working parts there and uh one small mistake will completely mess up your entire deployment all right so now what we'll do is we'll open up our code editor i'm using vs code you could be using anything else and let me bring uh vs code here all right and here all i have to do is i just have to create a main.go file and we'll be just using one dependency in this entire project that is it all right so this program is going to be short and we're going to code a bit quickly in case you're new to golang main.gov file is basically the entry point into the project and in this program since it's a very small and simple program we have only one file which is the main.go file right and the way main.go file starts with is you write package main on top and you import a couple of packages here other packages that you want to use in this file and you have the most important function from uh where basically the control of this project program starts which is the funk main all right and sorry i need two packages one is called the fmt package and the other is called uh the lambda packet so i'll say aws slash aws dash lambda dash co slash lambda all right and we need that lambda package obviously because we're creating a lambda function and fmd basically helps us if you need to go lang again fmt basically helps us with some basic functions like printing and all right so golang is very modular even printing is not there in golang so you have to import a package which is a native package by the way for uh printing stuff right and all we're going to say here is we're going to say lambda dot start and that so lambda is basically this package that we have imported and start as a function that that package gives us and here we'll say lam handle lambda event which is a function that we are passing to this function all right so this means that handle lambda event is a function that we'll have to create here so we'll create that function and lambda event and it accepts some things and it returns something right so what does it accept except it accepts an event so we'll say my event and it returns a response it can also return an error if there's an error and here we'll just basically return response right now let's define what response and event are so we'll say type this my event and my response are two things that we'll define here so my event is basically a struct similarly with my response is again a struct so in case you're new to golang structs are basically your own data types that you can create which are a combination of multiple different data types all right so if i'm creating a data type called my event it's going to have name which is a string and json what is your name by the way i have more than 100 golang videos on my channel so if in case you're planning to learn golang do take a look there are a lot of different type of projects and the way i teach golang is that i basically show you how to build projects and not just teach the basics right so it has just two things name and age all right event so string which is basically what is your name and end which is how old are you and it's going to store um an integer which will be the age out here all right and your my response duct will just have message which will be a string and it will be json and answer okay in case you're wondering why we have to define json like that we're just you know defining that for the purpose of golang golang understands string and end it doesn't understand json right but what we're going to send when we invoke our lambda function we're going to send jsons to it right so that's why we have defined how it's going to look in json so here in my response you already know that my response consists of message so it will say message fmt dot sprint f is a function that helps you to format your strings and you'll say percentage s is percentage d here's old now you have to substitute percentage s and so you'll pass those values here so you'll say event dot name comma event dot h so event will have the name is let's say john and how old are you will be the age so uh all you get in the response when we invoke this lambda function is we get john which is percentage s percentage string right the name is uh 32 years old or whatever like whatever you want to send here and here for the error you would want to pass nil because it passes response and error so for the error we are saying send nil for now and this is what the entire program is about i mean that's it 24 lines even if you remove these spaces it becomes even less but i won't remove that space so it becomes like let's say 20.2 lines that's it that's all we're going to test right now right so that you basically come to know what lambda is how it works and then once you're comfortable with it then uh we'll build the entire serverless stack project all right so now is a good time to go back to our terminal and we'll start doing some operations here now i'm obviously assuming that you already have aws cli setup right and now there are three things that you want to do in the beginning itself now these three commands that i'll show you here are from the official lambda deployment documentation so if you open the lambda documentation for aws deployment documentation you'll see these things these exact same steps right so this is nothing new uh and i'll copy and paste these in the description box below as well so that you can copy and paste them and also there's and you can easily find them on the internet so you don't have to worry too much about it the first command that we're going to paste here is basically a command that creates a role name right called lambda x which will have the right role policy documents and that's what will basically allow you to access lambda on your aws account all right uh so when i press enter in my case it it should give me an error saying that this has already been set up for my uh account ideally that's what yeah so it says an error code uh it already exists right now the second thing that you need to do is you need to go back to your function here and you need to create a file called trust policy.json and this is something that lambda requires right to be able to trust the program that you've created so i'm going to copy and paste some json code here and i'll share this code with you in the description box as well so that's all you have to do now these two steps like i said are directly from the lambda documentation now there are there's another third this is the third command that you need to now put in your terminal i'm not sure why it's not coming just one second yeah so this is basically pointing uh to the trusspolicy.json document saying that this is the you know rule policy document here all right so in this case also should give me an error because i've already done it all right it's already exists and now there's another another command so there are four commands till now right so this fourth command also is very similar there's some issue with copying and pasting that i'm facing right now so all that these functions are doing are helping you to basically set up your policies and roles and permission all of those things all right so now that the basic work is done and now golang won't basically sorry aws won't stop you from uploading and deploying your lambda function now because you have already the trust policy document so all you have to do now is you have to build your main.go file so you'll say go build main dot go so it says that um i have not installed this package so i'll say go mod tidy first this is what's really great about golang because it doesn't make let you make any mistakes right so you'll say go build main.go so it's built the so as you can see this main right this is the executable file which we want to uh send to lambda now before you send or upload anything to lambda you need to have that file as a zip file so you'll say zip function.zip and you're going to zip the main project right so now if i ls they'll have this function.zip which is the name of the file right so we will call zip now it's possible that your particular ubuntu terminal doesn't have this function called zip right so if you're on ubuntu it's very easy it's i think it's just sudo apt install zip and similarly if you're on powershell or on powershell it's also easy i think you can use the choco installer now package installer and on mac you can use homebrew to install zip and that's straightforward as in it just takes your main executable file and zips in into a file called function.zip and that's the one that you want to upload now comes the most important function right so i'll paste this function here and then we'll have to change the name of the function not sure why i'm not able to copy and paste it easily some issue wait actually i just bring out my notepad because i need to make changes to that uh program right so this is the entire uh function that we want to basically um the entire command that we want to run right now and all it does is it basically creates a lambda function and it gives the function a name and what we are saying is that this is the zip file function.zip and handler is basically main inside that zip file is main executable file and the runtime that you need is golang 1.x all right and here the name of my function is actually something else so that's what i need to just verify go lambda function 3 that's the name of my function so i'll say go lambda function 3 all right so i'll just copy and paste this command here and i'll run it everything seems fine right now one more thing that i forgot to mention is that this is my particular amazon account id you need to replace this number with your account id all right otherwise this program won't work it's taking a while because it has to create that lambda function also has to upload that function.zip file so it will take a while and then the last command that we'll build we'll be running will basically be for invoking that function so in the meantime while this function is running just copy and paste that other function here that we'll use to invoke so as you can see what's happening here is it's basically this function this command will invoke your lambda function in my case the lambda function is called go lambda function 3 right and so this uh part this i found from stack overflow this is not in the documentation if you don't do this and you pass json in the payload because you have to pass json in the payload right we have to pass json in the payload because that's how our request and response will work it'll be what is your name how old are you right and sorry let me just make this full screen yeah so what is your name is jim and how old are you as 33 right that's how our function is structured in case you don't remember this is what is your name and how old are you and the answers for that is jim and 33 and whatever happens like let's say even if there's an error or the response will be formed in a file called output.txt all right and if you don't so this is something that i didn't found find in the um lambda documentation decide to find from uh stack overflow because when i was passing my json i was getting some errors so just make sure you write this little you know text here and so this is your program now if you see here if this has stopped you know this is basically deployed and everything seems to be fine and it's giving you the latest version so your lambda is deployed and now you'll just say control c and now you want to just pass the last command let's try and invoking it and seeing what happens something wrong with my copy and paste let me actually start another terminal i will see it into the directory is called uh lambda something like that right sorry yeah user cd lambda and yt example and here yeah so this is the exact project that we're in and here is where i'll just run this command you don't have to necessarily run this command here inside this project directory but i'm just doing it because of habit so again it'll take a while to invoke so it took about four five seconds to invoke i say status score 200 and execute latest version which is called as dollar latest now how do we know uh that everything worked fine because we need to check for this file called output.txt so we told our lambda that you invoke this function and whatever output that you get by sending this payload into the function you write that in a file called output.txt so that's what the file we need to look for so as you can see this there's a new file called output.txt here you click on it and you say that jim is zero years old which is wrong because it should have been 33. so that means our program is misfiring i need to just check for that now so we'll just go through our code quickly and see the issue the issue seems to be out here because there's no question mark here so when we're passing this here right as a question mark or just remove this question mark for now for now just remove this question mark because if we remove add a question mark here we'll have to redeploy this entire function by uh you know zipping it right so for now let's just change our invoking function and copying it and pasting it again here and let's see what that what happens so we'll wait for it it has uh completed the execution now it shows jim is 33 years old right so what's happening here is basically it's matching this completely properly like even if there's an extra question mark it won't read this value right so just make sure uh these both statements they match and that's the only error that i got and everything else seems to be working fine so that's it you know that's your complete lambda function and deployed to the cloud when now when somebody uses it or you use it only then you have to pay for that particular usage otherwise everything is perfectly fine in this video we are building a very basic lead management system or crm using golang and go fiber and this is a completely beginner friendly video so if you have no uh hands-on experience with golang this is the right video for you to get get your feet wet and start working with golang now i'll be using a very basic database called sqlite so it will be very difficult for you to set up or start using okay and uh i won't be using any concepts that throw beginners off with golang with like i won't be using any pointers difficult advanced struct modeling i won't be using marshalling and marshalling i won't be using like channels and go routines i wouldn't use any of the concepts that people the beginners find really difficult to understand so this is a great product to get started the only prerequisite is that you should have sql lite installed ideally if you're on ubuntu uh it's very simple it's very easy to install sqlite just one command i think uh apt get installed sqlite you don't have to do much so with that out of the way um let's let's start uh setting up the project so i'm in my terminal now and it doesn't matter how you go path is set up we are creating a new project using go mod so that will create the entire package for us and do the package management for us so we can create this folder or this project anywhere in our computer okay so i'm going to create a new directory and i'm going to call the project go fiber crm i think basic and the cd into it and i'll also go mod in it i'll just give my username and then i'll give the name of the project go fiber crm basic now go mod in it creates a go.mod file which is going to basically contain the list of all the dependencies that we use in this project so you open this up with i'm opening it up using vs code you can use any other code editor and here i'm using uh if you if you go to your golang if you go to your vs code extensions the first few extensions that come up when you type golang just install those uh because that'll just make your experience better in the sense they'll rent the errors and the issues for you by default and i've i've already done that so even if you don't do it it's completely okay but if you do it then you're just able to find those issues much faster and easier the way we structure this program is going to be really simple we just have a database folder we'll have our lead folder and we'll have our main file now main.go file is the most important file in your golang projects and this is basically the entry into your project and in your lead you'll have a lead code go file in the lead folder in your database folder you'll just have a database.profile so with main.go this is how you start the main.profile right it's called main and the second thing that you usually write are the import statements for the packages that you might want to use and then the most important function here in the main.go file is usually or it's actually always funk main so this is how you write funcman you just create these two brackets and then you create these two curly braces inside which you'll actually like the function definition and um since i've only told you that i'll be using golang fiber for fiber i'm going to go ahead and install it so i'll say github.com now um since we're using this package whenever you want you've written down any packages and you want to install them you just have to run this command called id and you'll find all the packages that have been defined but not installed yet and we'll install all these for you so i'll go ahead and find the model for package and install it automatically okay what you want to do is you want to create some routes so we'll create some routes we'll say funk setup routes here and the routes will be simple there will be uh get leads right in the crm here there will be a create lead so we'll have app dot post new lead there will be delete leads so app dot delete there will be okay and uh now you've been calling this app but what is this app exactly app is basically an instance of your file so you'll call the fiber library like this and you'll say dot new okay and you'll go to the next line you'll say set up routes and you're going to pass app into this folder i meant function part folder so into this function which is set routes you pass app which is basically an instance of your fiber and by the way you've seen that this squiggly line has gone away that means it has done it's done installing the five word package for us okay now if you're passing phi app here in this function that means you have to accept app into this function right so this is how you accept it so you say fiber dot app i know it's there's a star here and it's a pointer and i said there's no i'm not going to using any pointers but this is just one little exception okay i won't be using it anywhere else but just to give it reference and to it you know refer to the app that's being passed into this function we have to use the pointer so in case you don't know what pointers are don't worry right now i'll be creating very basic videos and explaining pointers but for now you just have to remember that app has been passed into this function and we don't uh we just want to uh use it or call it by reference just remember that call it by reference as in we don't want to directly um you know use app and uh why and how it works and what our pointers all of that i'll be explaining a different video in a very basic kind of video for now just remember that you just have to put a star here that is it right that's all you have to care about anyhow so you have uh defined these four uh these three different things but i need one more okay i need one more it's called just getting one lead dot get and just get lead so how this is working is that for this new lead you'll have a route which will help you create a new lead and for getting all leads you can have get leads for getting just one lead using an id you can have get lead function and then delete lead function is will be for deleting a particular read with the with an id okay so uh now you want to have app.listen this starts off your server at the port 3000 and and you also want to uh connect to the database uh but what i'll do is i'll just define the database first and then i'll come here and then start we'll connect with the database now you want to create a function here called init database okay and you want to go to database.go and here you want to write package database we'll import a couple of things and we'll define a variable we will define a variable to be able to connect a connection or to be able to create a connection with our database so we'll call it dbcon as a representation or reference to db database connection and it's going to be of type corn dot d now gorm is basically uh golang orm which helps golang to interact with the database otherwise you would have had to write all those queries yourself but here you don't have to because you get the help of gordon and now that also means that you'll have to import god because god is not is an external library right so you'll say github.com slash jinzu which is the name of the person who's created gorm and then right corn you'll also get the exact um support for the exact database that you're using so the database that we're using is called sqlite inside corn we have something called as dialects and you get sqlite so dialects basically means language right so uh inside gone what what language do you want to use so we want to use the sqlite support language basically to be able to connect our co-language sqlite so what you want to do is you are put a slash here and then just copy and paste it here right and just run go mod id again and you'll get these two packages and the script line will go away so always just keep running uh go more tightly right so i just run it some time back and i got all the packages so your database.go file is complete now we'll come back to our main.co file here what you want to do is the database that you just created right the database file that you just created or the database package that you just created you want to import it here so you want to say github.com slash account slash uh the name of the project the name of the project is go fiber crm basic so just write that same name here and slash database this tells golank that you want to import the database package that you just created here in this folder and you just want to import that so once you import that then you can access the code that you've written there okay so this makes the golan code monitor in the sense you don't have to keep everything in the same file you can divide it into different packages and you can install or report those different packages into your main.com file and this is how i've imported the database package that i've just created into the main file all right um now um what i want to say is in my um main file our main function how to call a function called init database and i want to start a connection so you have both we have just defined the db connection variable right so you want to say database which is your database package which we are accessing using this database dot db connection which is the variable that you just created which is of type column.dp remember so you say database or db connection dot close at the end now differ uh is a statement that you can check out it's it's a golang statement which basically means that this line that we've just said that the connection to be closed will happen at the end when the function has completely run everything has happened after that only this function this line will run this command will run which will close the connection right so we're just making sure that after everything is done after the whole funk main has executed only at the end when everything is done just at the end just before the uh you know end of the program the last pro the last line or the last command to run will be this one database connection up close anyhow so um this in a database function that you have called here and we've defined here we can now start defining it properly so first you'll define a variable called error and you'll say database dot db connection just to remind you database is our folder the package that we just created here database.gov package and dbconnection is the string that we just created so we are accessing the database package in the database connection string just like we did out here and we also have our error and here we say gone dot open sqlite3 and comma leads.tv so what's happening here is that you use gorm to open a connection to your sqlite3 database the database name specifically is leads.db and you get that connection in this database dot connection or uh if it's not connected you'll get an error now with the golang what you do is you handle error red after every single operation that's taking place so just as this has happened that are taking place we want to handle the error right here itself so let's say if error modification you want to panic and say failed to connect but if everything went well then you want to say connection open database and you'll say database dot db con dot auto migrate ampersand lead dot i'll explain to you what this is and at the end you want to save print ln database migrated okay now lead right lead that you see here you want to define the lead now uh the reason we're getting squid lines here is that fmt is not imported fmt is a package that helps you to print now golang is so modular that it doesn't even have the ability to print on its own so it's there in a package called fmp that you have to import into your program and then you have to use print println and this keeps go angry light and fast so um you also want to have um yeah i think this this looks good yeah so you want to uh now we want to talk about lead university basically lead is going to be this package here that we'll define right so firstly we can find this package we can say package lead right just like package database we defined it's going to have some import statements and most importantly it will have a struct now we won't have any uh difficult or anything these trucks and you know relationship between the structs and modeling all of that we don't have any any of that just have one struct start is basically a data type that you're creating on your own so there are some data types that you get with golang like string and hint and that's all we're using we're just using string in it in this video so you get these kind of data types with column write string and but what if you wanted to create your own data type uh with the combination of strings elements and you can do that with golang and it's called struct right so structs your own data type that you're defining out here and you're saying that lead is of the data type struct and the struct is going to have is going to be modeled it's going to have name company email sorry company email and phone so for a lead management system we'll just have name company email phone that's it phone will be inked now what i'll do is i'll just create proper spacing between them so that it all just becomes a little more readable and um that's that's about it actually so this is how what you need is going to look like right so when you go back to your main.go file you want to now import that lead right so right now obviously the lead file is not complete but eventually at some point of time will be completely complete but you would want to import the complete lead package into your main.com file because you want to run some operations on it and um so how do you import it you just do the same thing just this is your main part of the project right uh your project is github.com i killed slash go fiber basically because that's how you had defined it when you was doing a go mod in it right that's how you initialize the project and uh you can always put a slash here and you can say lead and it'll know golang will know that you're talking about this lead package out here now uh all these functions right so get leads get lead newly deleted functions we can either define them inside our main.go file or we can define that in the lead file and keep our main.co file lean and simple and small so that's what we're going to do we're going to keep all those functions in our lead.go file and we're not going to keep them here so that means that um those functions will be in a lead package and that's how you refer anything in another package in a lead package we'll have these functions get leads get new lead and delete and the way to access them will be like this the documentation dot okay now you want to define the actual route right so that will be slash we'll keep a lead right so if somebody using postman or using um you know girl hits this route api slash v1 lead then he is going to be able to get all the leads if he uses the get method if you use the post method on the same route you'll be able to post a new lead and for the um get one by id and delete by id it'll be same but at the end there'll also be that id of uh you know of the lead particularly cool this is what you get right this is how you're set up the routes now the program looks complete right and we'll head over to our lead.go file now so it's saying that i don't recognize what gom dot model is it's giving you a squiggly line that means you have to import the corn i think my video had stopped for a while i've just switched it on back again anyhow so with import uh you want to import the god right so you'll say github dot com slash gen zoo slash now you notice that it doesn't give you a squiggly line out here and that's because gold line already recognizes it because it's already there in your co dot mod right ginger.com is there so you don't have to run go more tightly again you just have you can just um keep this or import this into any um in any file once you've done go mod id once you have imported it in your project right so now you'll again get your go fiber so i'm just going to go to my main and just copy co fiber because um i'll be defining the functions to work with those dogs so that's why i need go fiber here again and similarly that what i need uh in the database the sqlite i'll just copy and paste that also here all right and i also need access to the database so what i'll do is i'll just copy this line and i'll put it here so soon in a while i'll need access to the database right the database connection all because i have to um for those get all leads and post it i'll have to work with the database so i need access to database connections that's why i've imported the database as well and now i want to define all these functions that i have in my main.com file which is basically get leads get lead new lead and delete so let's do that quickly so first function will be get leads second function will be get just lead third function will be new lead and fourth function will be delete delete now they'll have they'll accept some things and then they'll have their own uh function definition so just do that for all of these now what are they going to accept right they're going to accept c which is basically your fiber dot context fiber rcdx in case you have no idea how context works don't worry i'll have another video and the basics on explaining context but this is a very basic concept of golang and in case you know already know that's really good but if you don't know it just remember that to all these functions that are uh being driven from these apis right from the apis you hit it out and you call a particular function there you have to pass your context to your fiber okay so i'll just give you a very basic idea what this is doing is that this function now can start to work with the data that's coming from the user so for example in my get lead function in my delete function i'll need to use id right and i can use that i can find that id in my c dot params basically c will have all the data that's coming from the user so let me i'll show it to you with an example you understand it so for example in my func get lead now i want a particular id right i want to read off particular id so that means i need to define a variable called id and i can now get access to the params that the user is sending the user is going to say that from the postman or curl that hey i want the i the lead for this particular id so that id you'll have access to that id using c dot params so this is why c which is of type type fiber dot context is important so uh what we'll do is we'll just copy this and paste it everywhere make sense now um let's just finish this function off first so here i'll have a variable called db which will be of type database.connection and i'll have a variable called lead which is of type lead now i have the id that the user has sent to me that's saying that hey i want the deal of this id and i'm now going to my database to fetch the data for that particular id and what i'm saying is that db which is my database or dbconnection right which is the instance of the database session that's going on right now i will find in it the lead with the particular id so i'll say lead with the particular id is what i need and we'll say c dot json lead so we are able to also respond using c the fiber context will also respond we are able to send the response right so we are able to work on the request we are also able to send the response using c dot json and we'll send the lead in the json format okay so this kind of saves our effort from marshalling and marshalling now with the get leads we'll do the same thing we'll say db is equal to database dot daily connection and we'll define available leads which is of type lead but it's a slice now when we say get leads we are basically saying that get all the leads that exist in the database you're not saying that get a particular lead with a particular id we're saying get all the leads in the database to do that you need um something called as a slice which is almost like an added you need a slice of all the leads right so lead in this case is the struct that you've defined and when you say slice of leads that means that there can be multiple such leads with this particular struct right um or in short uh in if you're from a javascript background you would understand that it's a it's an array of objects it's not just an array it's an array of objects that's what a slice is okay so you have variable leads and you have the slice of type slice delete and you'll do the same thing you'll say db.find and you can say db.find because db is the instance of the session for database connection right so you'll say db.find and you'll get all the leads and you'll response send the response you did just see.json will say it needs to send all the leads similarly you want to also have uh the code for new lead and again you'll start with db is equal to database dot db connection and you'll define a variable called lead which is new lead and if uh is equal to c dot parser lead header or equal c dot status as the three dot send error return okay so what's happening here is you get um you use uh body parser that you get in your fiber right in your fiber package you get access to body passes it parses the body of the lead data that the user is sending to you so the user is using postman mostly postman or girl and it's sending you the data for a new lead this data needs to um you know uh checked first so we'll parse it we'll do the body parser and if there's some problem with parsing it right it's going to send an error so this error is 503 that we're sending here but if everything goes well we'll just create that lead so let's say dot create ampersand lead zero json and once you have created that lead in the database you want to send that lead just to show the user that hey this is the lead i was just created in the database right now and uh this is how you create a new instance of the lead okay so the new lead function is quite simple is just using body parser to go through the data of the lead that the user has just sent and then checking if there's an error or creating a new lead and then sending the response with that same read i hope that makes sense now delete lead to delete a lead you need a particular id right because you want to delete a particular need and so we'll say id is equal to c dot paragraphs id and you'll say database is equal to database dot table connection we will define a new lead of type lead when you when you write something like this right you say var lead lead right you've done it here also but this is um you know um i probably didn't realize that maybe it might confuse some some people right so lead is the struct that you've defined right it's the data type that you have defined which is almost like var lead could be an end could be a string or could be a lead lead is your own data type here so lead is the name of the variable whereas lead is the data type which in this case is lead itself which is a start okay now you want to say db dot first lead comma id and if lead dot name is equal to is equal to none we'll say c dot status 500 dot send no lead found with id and you'll return from here and say db dot delete never send elite and see that send delete successfully delete it so um we get the id right using the same method that we did for get lead sorry this lead here is actually capital l right so i hope you can see what the issue was there shows that there was a small l here the red written lead but it will always be capital l because that's how you've defined this lead start okay so delete lead you got the id using the same method that we did in get lead you got the id right from c dot params then you have db which is the instance of the database connection then you define a lead of type lead struct and then you find the first lead that you find with this id now if you if you uh if the name of that lead is nothing which means that lead is not there that means that no lead was found with that id but if that was found then you'll just go ahead and delete it and you'll say lead successfully deleted that's about it that's it that's your lead.go uh file and then there's only one thing we are left with okay and uh this is the thing that sometimes throws people off uh mostly people who are coming from a json background or from a javascript background is that javascript understands json by default right so whenever javascript developer goes to another programming language like golang or python or java or anything else rust ruby whatever they get confused with this idea of that how can a language not understand json right it's because json is javascript object notation and obviously only javascript understands it natively but all other languages like golang we have to massage uh the data the you know the language to be able to understand json so what you need to do out here is with name you'll have to say json name and you'll say json company so json email json phone what i have done is i have used these backticks and inside that i've used uh said json and i've used in double quotes name company email phone number like that and what's happening here is that um we're telling golang that in json this is what it's going to look like so for your reference uh hey golang for your reference you're saying that it's name with capital n company with capital c email with capital e but the json that you'll receive will be with small n small c small ds small b right this is how the the json is going to look like uh going to look like and we we're expecting uh golang to understand the json right so this is what i basically wanted to show you and when you say um you know that c dot json and in bracket leads you're basically saying to go like that hey whatever you've received from the database now you have to convert it back into json and select to the postman or the terminal whatever okay so what i'm trying to say here is that golang does not understand json and it understands one's constructs and it can only function or perform operations on that struct that it understands and then it then again has to convert something into json and then only it can send it to the response which we will understand or our front end will understand so this was basically your lead. go file and database your dot co file is complete as well and your main.go file is also complete and i'm just checking uh just to see in case there are any issues um in my main file i need uh gorm as well so what i'll do is i'll just go ahead and i'll get the gorn fiber and sqlite all these three packages i'll get into my if i already have so i'll remove that from here i just needed these two packages here in my main.co file as well okay so i think we are ready to be able to build this file now so you want to uh um before you run this file you want to build it so what you'll do is you'll head back to your tunnel and you'll say go build name as soon as you build it you see this file called just main it's just called main and what that means is it's an executable file it's a dot exe file it's executable and uh like dot exe uh if it was windows it would be dot exe file but whatever uh operating system you're using you'll create and create a uh operator like an executable file for that operating system so that you'll be able to run that program and now all you have to do is uh go run main.go and it'll run the program for you as soon as as soon as you do that you need to see these two things connected connection open database you have to see that database migrated in case you don't see any of these that means your program is not working properly and you need to check the code i'll push the code to github as well so this means that our project is working like we see this nice fiber uh you know text here and then you have your port 3000 on which it is working so everything seems to be fine you have four apis for hunters okay so now all we have to do is go to our postman and this is the collection that i've created for my go fiber basic uh project there's an add lead here as you can see right so i'll create this ad agree this lead so this had an id it has created ad updated at delta and then you have your name company email phone now these three time stamps right created updated deleted these can be added automatically uh when you add some data and these are optional right now you don't have to add them but but you may have seen that in many programs it's added automatically and i've shown how to do that using the time package in my other projects since this is beginner friendly project i have not used the time package i've not shown you how to use those timestamps okay and i'm sending it manually from the front end or from postman so here i'll just change the id i'll create another record i'll call this alex clinton let's call him alex clinton we'll call the company name microsoft and email would be alex at microsoft.com and we'll change this phone number a little bit we'll send and you can see that let's create another lead for us if i want to get all leads i'm uh you can see that i'm in the same apis that i have defined here right so if i go to my main.co file um api slash v1 lead so you come here localhost 3000 and api slash v1 that's the apa you're on you send and you can see we have created these two leads so it's working perfectly you created two leads you can see those two reads now you want to get a particular lead right so you'll come here and you will now look at the api uh which is the get api for the particular id in the end you want to add an id right so in the end i've added two i do that i get my ramsay beaters and if i add one i get my other guy and if you want to delete a particular lead it's the same right same api as in same route but the method is delete so you want to change your method here from here to delete and you want to delete the lead tool so it says lead successfully deleted and now when you check get all leads they'll show you only one lead make sense that means your entire project is working this is your simple lead magnet system this is a very simple beginner-friendly project we'll be building an hrms which is a human resource management system and we'll be using golang go fiber and mongodb so essentially you'll be learning how to use go fiber along with mongodb but um in a in a format of a small project so it's very it's a very good way for a beginner to get their feet wet and actual uh you know up applying what they've learned till now now since this video is very uh beginner friendly uh i won't even be having different files i'll be having everything in the same file may not go file so we won't be learning about project structure here because it's ugly again for complete beginners and but in case you want to see more project complex project structures and design patterns and all that i have a lot of projects already on my playlists without further delay let's get started and i'll just open up my terminal now you can see i've opened up my terminal now i'm using powershell on windows for this project and it doesn't matter how you've set up your go path or how you've installed go we'll be using go mod and that means that we can have the project anywhere and go mod will handle dependencies for us so i'll create a new directory for myself for this link project i'll call it go fiber hrms and i'll cd into it and i'll open up uh so before i open up this on on a vs code or any other code editor i'll go ahead and say go more in it which initializes your mod file and you'll give it an absolute path you'll see github.com and the name of the project go fiber hrms okay and now you can go ahead and open it up in a code window i'm using vs code vs code works out really well for golang so in case you're using something else just drive your code once so as you can see there's uh already a file called co dot mod that exists for me right and it mentions my uh name of the project and also mentions the version of golang that i'm using so that if anybody else takes up this project they can easily install all the external packages that i'll use using this file and all the external packages that we'll install in our project for example the drivers that we'll use to work with mongodb you'll see them listed out here so as i said we'll have only one file in this project and um so main.go is the file the most important file usually in the golang project and what you want to start off with is you want to say package main and you'll want to import some things here okay and after importing those things that we'll talk about in a while mostly around the things that we'll import will be mostly packages around mongodb uh we also want to create a instance instance of a session with mongodb so that we're able to interact with mongodb and it will be basically a struct so instance struct and you'll have a client and you'll have a database so a struct is basically your own data type so you get some data types with golang like int string uint you know all of those float and all of those different uh data types but what if you wanted to create your own data type right uh you can do that in golang using something called a struct almost like an object with javascript and so it will have two different things one is client one is db and uh here we'll have to write some things which i won't write as of now because we have not installed those packages but to be able to work with this struct i'll need a variable called instance now this is how you define variables in mongodb in golang you have this variable mg and subtype this is the data type so it could have been string it could have been end but right now for this uh for what we're doing right now it's instance among which longer sense is our own data type that we've just created right it's a struct it has a client it has a database okay so i also want to define two uh constants so the first constant will be the db name name of the database that i want to work with db sorry name and it's going to be called let's say we call it fiber hrms and don't define a constant for url now in this video i'm going to be using the localhost mongodb that means that mongodb is installed in my local computer and it'll be running on a port and mongodb usually uses 27017 as the native port now you could be using mongodb on your local machine like i am using to keep things simple but if you are using a fully managed service like mlab they will give you a link to embed in your program and that's the link that you put here in the mongodb uri okay so in my case i'm using localhost so this is how i'll write the link so it'll be mongodb and after these two slashes you'll put your own actual link that you got from your managed service in my case it's just localhost and my port is 27017 the way you have configured up your mongodb also makes a difference here because you might have to write your username at the rate your password and then uh your localhost so in my case the way i have configured my mongodb i have not kept any username or password for my admin user to uh as an activity with mongodb without recording any username or password uh in case uh you don't know how to set it up like that there is a video on how to install mongodb uh i think it's long i uh put it up long long back so you'll just have to search red bit on my channel and you'll find it it's very simple it's very straightforward right you just set up mongodb without any users or passwords it's just you know easier to work like that especially if you're building very simple projects right and here you want to add the db name the dv name is fiber hrms and that's what will be added so when your mongodb gets connected we'll get connected to 27017 and by default to this database called fiber hrms now comes an important part which is basically how you'll define your employee now in human resource management system means it's a company and they have a database of their employees that work there so the employee will be a struct now um you can you can manage name like name as a string or you know salary as a as a string or as a number but how do you manage all of that together for one employee right so that's why you create a struct right so there are these data types that golang understands then there are these data types that you can create called structs that you can make go like understand because they have these uh different fields like for example there'll be a field called id field sorry field called id field called name just name and field called salary field called age and all of these fields will have a data type like string for example name will be string salary is float and age is also float right so now these fields like id name salary h there are data types string or end or float whatever so that means golang can understand what we're trying to say right but all of those combined make up a struct and since golang understands those individual things like id name salvage it will also understand this whole start right which is now a new data type that we've treated for uh argues okay now uh there's there'll also be something else that i'll add here but not right now and i'll explain to you what it is but uh just keep this like this keep this as just a struct for now okay now you'll have a function for connection which basically helps you to connect your co-link to mongodb so you'll have the connect function here and every function basically takes in something and returns something so error is what's returned by this function if things go wrong and it takes in nothing basically so this so there are these empty brackets right and inside this will be a function definition that we'll write in a while and at the end will be funk main so funk main is an important function usually the main file funcman is the most important function and that's where the control of the program uh usually begins okay and um here you want to first define your app now if you've used um node.js by any chance uh and if you use express because you have to use express with most days right mostly so if you've used express that then you know that you have to define the app variable in the beginning which is basically an instance of express and that's how you interact with express and exactly that's what we're doing here because fiber is the equivalent of express so express is for with node.js and fiber is with collage it's an exact equivalent but fiber is like i think they say it's 10x faster or something like that it's really fast basically that's all i need to know okay so um now when i say fiber dot new that means i should have had the fiber package so this is how you install or sorry in the import statement this is how you import an external package so you say go fiber slash fiber slash v2 sorry it's a small v okay so small v and um you also want to get some mongodb related packages but for now let's uh let's just keep it this much and what we'll do is we'll go over to our terminal and whenever you import a new package right you have to say go mod typing so that golang will go online and find the model package for you and will install it in your program now after your fiverr definition you want to have the standard functions so which are also your routes right so the first route that you want to define is slash employee and this is the get route then you'll so this this the first route with the get method is going to help you get the list of all the employees that are there in your database then you will have a post route and then you want to have a put route and a delete route okay and for post route the route will be the same for put there will be just an id after employee for delete also there will be an id and the way you start off a function is basically when something lands on this route or some or somebody calls this route you want a function to get called and that function basically can return an error if something goes wrong and it will have a definition right the function will have a definition the function usually takes c which gives you fiber dot context you know c which basically is type of fiber which you get access to from here from the library fiber dot context now um there's something really important here for you to understand is that um whenever you have a function like this like a route function you want the request you want to be working with request and you want to have the ability to send out a response a json response by request you mean whenever the user sends let's say from his post manner from curl whatever the user sends to the program and it could be an id it could be uh like in the in case of the post request where you want to add a new employee it would be the new employee data right the data for the new employee so that will all come in the request so you need the ability to be uh to work with that request and you want to be able to process that like let's say you added a new employee or you depleted an employee using the id or you updated an employee using the id and you need the ability to also send out a response back to postman or to the terminal so uh both of this can be done using uh fiber.context and c is how you're going to be accessing the response and request okay so this is what was important for you to understand now uh before you start with all this right you also need to be able to connect with the database so you'll call the connect function here and connect function exactly the same function which you're going to define out here so um what's happening here is you'll have f error you'll handle the error here itself and error not equal to nil then your log dot fatal here so the log library helps you to log out errors and we have not imported it here so we have to import the log library right here like this all right and um what you want to do now is we want to start creating our connect function so convert your connect function and we'll say dot new client basically going to create a new client for mongodb now this word basically comes from the library that we have not installed or imported yet so let's go ahead and get the mongodb libraries the first one is go.mongodb.org driver slash so firstly just get actually just get longer right and the spelling here is uh wrong so just make sure you write the right spelling which is mongoose and driver okay so that's the main important library now this library has a few more things that you can get right the so the first thing that you can get is are the options so let's say go dot mongodb dot org slash driver slash and then you'll get some options and then has some bs on the primitive that helps you to create that id right so we'll have to import that as well so you'll say go.mongodb.org slash driver slash vsan this will help us to create the id for every single record there will be a ps1 id and we'll have again mongodb.org driver slash nissan slash primitive now if in case you're worrying that you'll have to remember these four legs you don't have to you just use it once here and every time you now connect with mongodb you just have to copy those four links i didn't copy them i could have copied them and any other tutorials will see online they will copy them but i'm just showing it to you you know so that uh you you understand that you go to go.mongodb.org website then you go to the mongodb which is the main driver which is like the main apparent library then you have like uh which is the package the orm that you use and then you have your options then you also have your psalm primitive okay so that's why i i just wrote it for you to see that they're all linked and all related so that you're not just blindly copying all of that okay but mostly from now on uh once you've done this project you just have to copy and paste these four lines every year so what happened is when i when i just uh pressed ctrl s to save it uh there are some plugins or extensions that i'm using for golang that basically recognize that i'm not using those packages right now so they have removed those packages for me so i'll control z and not save it as of now but if i try and save it it'll remove those packages that i'm not using so it basically helps with error solving and you can also go to your um what you call it your extensions and you can just write golang and the first three four packages that come just you can just install them they just make development little easier um now now that we have installed or imported these packages now it's going to be very easy for us to work with our connect function okay so you say mongod.net client and then you say options.client dot apply uri so this function right the options dot client dot apply ui you already get from the package that we're using and apply uri is a function where in that function you pass basically your uri that you've just created so all it's doing is it's going to apply that url and basically going to connect and you know create a new client for you and for that url that you've just created or just given to this program um you'll get access to this this whole thing as in the complete connection instance using the client right so whenever you want to work a client you don't want to keep writing this all the time right you want to be able to uh you want to get all of that in one variable that you can use later on so that's what the client is in this case and in case you don't know what this is this is the walrus character this basically um you know defines a variable and also declares declares and defines at the same time so here you also want to have something called as a timeout now there are some functions with mongodb that are blocking functions like insert right and you don't want it to block the entire program so you want to always have a timeout and timeout basically with this mongodb package for uh specifically uh it gives you it uses the context package that already has to give you this ability to have defined timeouts so this is how we define timeout so you say context dot with timer so in case your mongodb is not responding or something goes wrong or insert is taking too long you have a timeout you don't want to block the entire program and uh now this is not compulsory but uh this is a good practice i mean you have to it's not like without writing this the program won't work it will work without it completely fine but uh you know i recommend always writing this down okay so you'll see backgrounds comma and you can give any time here you can give a time of 10 or 20 or 30. now what you'll notice here is that um time as soon as you write time it's not recognized by golan that's because golang is so modular that golon doesn't doesn't even have the ability to print things or uh even the time package is not is even the time ability to understand time is also not inherently available inside co-language so this basically makes golang very lightweight and very fast okay that means that time um is not understood by golang that means it's a different package altogether so you'll have to come up here and you'll have to install time package on your own now uh the extensions that i'm using were able to get the context package for me automatically so when i used context out here even context is not understood by golank but somehow the extension decided to get the context package for me automatically i didn't have to do it anyhow there's a quick line here that means context there's no function called with time out and that's because uh the o should have been small and now golang starts understanding it very quickly you get a squiggly line here with client and error that's because you have defined these and you have not used these as of now and golang has a problem with that so in case you define something and you don't use it golang has a big problem so we'll quickly uh we'll use it we'll basically use these two variables okay now um you want to run this cancel script at the end of this program and that's why you use differ and now you want to say client.connect and you want to pass this context here so here um i forgot to show you that ctx and cancel are the two things that you'll get here right so when you say control c whenever you run your program right and determine you say ctrl c will basically cancel this it'll have that timeout here directly it'll just cancel the entire operation whatever is running out there so um now you have client.context cdx the context is what you will pass here to be able to connect the database with the right context and you will again get that in the error if there's an error there you'll get that in this error variable that you'll handle now and you'll also have a variable called db so we'll say client.database and you'll pass the db name here so you've connected to the database uh to the you know mongodb but you also want to go into the right database right and this is how you do it and uh you can you'll be able to use this now um the database using this db variable so this error that we have received that we may have received if things went wrong while connecting or while creating this new client those errors will handle right now so let's say if error or equipment and by the way this is a common theme with the golang that always when you write something and then you might expect an error there you will always handle that error just there itself so here we will handle the error and we'll have return errors now you might remember that we had created our uh mg here right our instance mg and here we'll say mg is equal to instance then you'll have client comma db and you'll return nil from this function okay so if you created your mg which is your instance which is a flight start and the way the values here for the client and database right have now been set so this is what we did here in case you didn't understand is that for the client it comprises of two things remember struct is basically your own data type and in this case it's longer instance which is a struct and has two things one is the client the other is the database so client means the client mongodb and database means that database name that you want to connect with and that's why we created this db and that's why we created the client these two variables here so that we're able to define our own start complete sort and mg is basically what we'll be using to you know further on if you want to work with the database so that's what your instance consists of now here you want to say that client is of type mongo.client and db is of type members make sense right now i know i said i won't use pointers and this star is basically a pointer so what you're saying is that it's a reference to dot client and mongod database if you don't understand pointers right now it's not a problem you don't have to uh you know really worry about it i'll have really basic videos coming up on what pointers are and how they work and why they're used for now here this is the only place where you'll be using it so uh and also the other place where uh we're passing a pointer to the fiber dot context so just have to remember that you have to put stars in front of these for now and we're just passing these by reference about pointers i'll create like a 20 30 minute video just explaining pointers so don't worry about this right now okay and there's no advanced pointers getting used here just just for this part so don't worry uh anyhow now coming to your uh employee start now there's something that i want to do here and i think right now is the right time to do that before we start creating all these handler functions for our routes so um one important thing that i want you to understand is that um golang does not understand json natively on its own just like if you're coming from a javascript background you might feel that you know json is always is basically understood by all languages and javascript people have uh this confusion because they feel that javascript understands co-lang json so that means all languages will understand json but it's not like that is because json is javascript object mutations only javascript understands it natively all other languages have to use some packages to be able to understand it in our case we have to use um a package called json we have to do a lot of encoding encoding and marshaling and marshalling basically for understanding and working with json and but in this case since we're using fiber fiber takes care of a lot of things for us automatically by default and it's all happening under the surface like all a lot of marshaling and marshalling is happening under the surface so fiber makes things very easy for us uh but otherwise uh by default uh golang does not understand json right so that's why we in whenever you define a struct and the struct is going to actually represent uh the data in the database in your mongodb which understands json by the way it's a javascript database and uh the data that you're getting going to get from the user as a request is also going to be json right so when data comes from the user as a request to golang it does not understand it because it's json and when data comes from the other way from the mongodb uh to golang and then golan has to send it to the user again golan does not understand it because it's coming as a json so this is why you have to tell golang that hey you understand id as string and this is what it's going to look like to you right id is going to be string and names interesting but in json it's going to look a little different so we just have to tell we just have to help uh just go like here and we have to say in json this is going to look like this man id and we'll also write omit empty for id and as you have may have worked with golang it also sorry with the mongodb it also needs pson for the id and this is how it represents id at the database level id comma format now when i i'll show you name also and then i'll explain the difference here okay so what's happening here is name is understood by postman is understood by your terminal when you uh or by the user when you send a girl request right name is understood as in json as name with small n whereas golang understands it as name with capital n and for column it's a string right but when it comes to id um the postman stands just as json id whereas mongodb stores us at as bson which is underscore id so this is why we have written bson again right for this for mongodb i hope that's understood and then you have your salary which is again json and your age which is agent json right so all of these fields they have small n small s small a whereas for golan to understand and go like to work with this information it will be capital n capital s capital a so now we want to start working with our main functions the main handler functions like get and post would delete all of these functions right and the route handlers so we'll start with get that means we want to get all the employees from our database to do that you need um like i told you golan does not understand json right and you'll get something from the database golang needs to understand it and go language to send a json response to the front end or to postman now to be able to work with that i need my a variable called employees and it's of type employee right so this is how you define a variable you say this is the variable name this is the type and you see these two brackets here that means it's a slice so it's okay if you don't know what slices slice is basically like an array but instead of containing just numbers it contains actual objects by objects you mean basically all of the things the multiple things that this area will contain will be an actual uh employee the whole employee right so this means that if you're coming from a javascript background this would mean that it's an array of multiple objects so now you initialize it using the make command and employee so um you've defined your employee variable right this will help you to work with the records that are fetched by the database from the database now to get something from the database you have to use um the find command that mongodb already has right so the find command you usually send a query in our case since we want all the employees from the database that means the query that we have to send is completely empty or just two empty brackets okay so we'll have to define the query here so query is equal to the sound dot t and inside these two curly braces you'll define the query usually in our case the query like i said are just two empty brackets because it's an empty query so this is uh the query basically so we've defined the query now you want to use the find function that mongodb will give you and inside that find you will pass query right the query that you've defined here but you'll also pass the context right so you'll pass e.context and you'll pass query here so i hope that's making sense now um this find function is available to you inside mongodb you know that already and how are we talking to mongodb in our program we're talking to it using the mongodb instance that we have defined here right the instance and the instance has something called as db so we want to uh target that instance and we want to talk to the database exact database inside that we want to talk to a collection collection is like a table so with mongodb you have collections and with an sql database like post like postgres or mysql you will have tables so if you're familiar with tables it's the same thing this is a collection so you want to go to that instance you want to go to the database and you want to go to the collection and then you want to basically uh run the find command that means you'll go to the instance mg dot you'll get the database inside mg right so it's mg and this database you've already defined the variable there already it's all be set and dot you want to get the collection so the collection so it's c capital and everything else is small collection is employees and you'll say dot find and you'll find the query and here what you get back is usually the cursor basically it'll have will have all the uh employees records or you'll get back the error so now you want to handle the error so you'll say error and for the error you want to return a status of 500 which is basically your internal server error you want to send a string which is your error string basically sending the entire error itself you've defined your employees already here okay one small mistake that i see here that i've made is that this bracket is not here it's actually here the closed bracket because it's a slice right it implies the slice this is how you find the slice there's two brackets and then employee all right now what you'll do is you'll use this cursor and here also i see one small mistake is that d is going to give you capital we will be small and now go language understand it so that's why the squiggly line quickly goes away all right so now what you want to do is you want to say cursor dot all c dot context comma ampersand employees when i say ampersand employees i'm basically passing a reference to this variable employees that i have sent and what's happening here really is basically whatever data we've received in our cursor right and from this function that you've done here cursor which is all the data of all the employees from the back end that has been received and this is going to basically convert that into a format into the structs that are understandable by coolant so that's why you pass these employees right so in in the end you'll get um employees right but that will be basically a slice of multiple different employees and we did this because gold line cannot understand json which mongodb understands and when mongodb sends some data from by running that find function you don't need to convert it into something that golang understands right and this is how you've done it so you'll say if error is equal to sorry in front of this you want to say if error and error is not equal and you want to return c dot status 500 dot send string error dot error right and here you wanna return if everything goes well you want to return the employees that you just you know now converted employees was that variable that you defined which was a slice of employee right that means multiple employees will be there and that basically is what you got from the database you converted into a nice uh you know understandable and understandable format and in json you sent it in json to as a response to the front end okay so i hope all of that makes sense now we'll move towards our post function so we'll make some space here for for post function we'll have our func and similarly this function will also accept a pointer to fiber dot ctx which gives us access to our response and request this is how we're able to talk uh use response request and it also does a little bit of marshalling and marshalling for us like here we did c dot json so it can do some mastering and marshalling for you by default it does take a lot of work away from you and gives you some abstraction so here you want to find your collection so we'll say collection is mongodb dot database dot collection and employees so instead of uh saying this again again mgb dot db dot correctional employees i've defined it and i can now use it in a variable called collection and i'll create an employee now um when creating something in a database right you have to use the insert function that mongodb will give you and also you will get just one employee that one employee data that you're getting from the postpan that as in the user will send the data of a new employee and that that new employee uh right variable is going to basically go to the database and this is how we'll define that employee variable is equal to mu so when we say this right um you can define it like this or you can say var employee and employee you can say like that or you can say implies equal to new employee all that's doing is that it's defining a variable employee which is of type employee you know the employee structure that you want to define which has id name salary image right so now you have defined your employee as well and what you'll do now is um you'll get some data in the request you'll get the data of an actual employee as in the user wants to add a new employee so you'll send a new employee data like name and all those different things uh your name and salary and age to this api and this api needs to now read that information and it does that using c which is basically your fiber context dot body parser so you'll say worry parser and when you say employee here that means all that data basically becomes formatted in the format that you need and you get it into this variable called employee right so it basically passes the body which is json you're sending from json into post from postman to this guru lang program into struct that golang now understands and after you've done that you want to handle the error so you'll say error is equal to c dot body parts are implied and if error is not equal to nil uh there can't be any space between exclamation mark and is equal to and here you return c dot status 400 dot send string error dot error okay now we always want mongodb to create its own ids and this is why what we'll do in the beginning is we'll say employee dot id equals zero this force is mongodb creates one id and now i want to take this collection that you have defined here so it's good that if i define this as a variable because i can now start keep using it i don't have to always write this again again so i'll say collection dot insert one now insert one is a function that i get with mongodb so if you're familiar with mongodb and the functions that you get mongodb it's really easy to understand you can insert one insert one basically takes data and inserts that into a database just one data into that insert one function you'll pass c dot context comma employee so you received some data in the body you used body parser to convert that into employee which is your employee struct and that employee stack basically is your is what you're sending to the insert one function along with the context and whatever i get back from this function after inserting right i'll keep that in a variable called insertion result and also an error so if the the error is there then i'll handle the error if error is not equal that is return c dot status 500 dot send string error dot error spreading the return is wrong now after it gets inserted it will come in this variable called insertion result while you'll get an error and this error will handle it right now itself and we want to do something with this insertion result what we're going to do is we want to um get the id from this insertion result that you get right then this id we'll use that to search the actual record uh that has just been inserted in the database and then after finding that record we want to return that to the front end okay and this makes us doubly sure that whatever we did the post request for right now it was inserted into the database and we can make it make that short by actually going and searching for that record using the id and then sending that record and this makes it very sure that uh this data was actually inserted in the database make sure yeah that makes sense all right so um here first i'll handle the error okay quickly so if error is not i'll give some space here then you wanna do something you wanna return c dot status 500 dot send string and error dot error all right now like i said you know we want to take the insertion result which is insertion result and we want to get we want to we want its id right so we want the inserted id and using this id we'll create a query and then we'll find the record that has this id to check if what we just inserted right now using insert one was actually inserted in the database or not okay and so let's say value is equal to insertion result inserted id and basically we're building up a query right so the key is id and for that key which is id the value is this inserted id that you just received and close it with inside another pair of curly brackets and say filter is equal to this one dot t just like you had created a query here for get which was um bs on the d and it was the query was empty right now you have vsan.d it's called sorry it's called filter not filler filter and based on these and the query has key which is id and the value of id is basically in session result that you just receive right now and the inserted id of that and you want to get the created record that you just created how do you get it you use collection dot find one and you pass c dot context to it and you pass this filter query that you just created you pass it there and that's how you get the created record so i'll repeat again you uh inserted the employee data that we just sent using postman then complete empire data and you used insert one query to insert that data of employee and you got that uh you know whatever you got back from this function was stored in insertion result and that insertion result also has a variable called inserted id which basically has the id of the data that just got inserted and you keep that um you know to to build a query and you keep that in this variable called filter and this filter is basically what you send to find one function and we're just rechecking that this data was created and then you get that into this variable called created record so this is the record that was just created right now by you and this is what you want to send to the front end so you will create a variable called created employee now want to structure and format that data right so you say that created employee is a variable of type employee which is your own struct right so created employee will have id name salary type employee and you want to do you want to say created record dot decode and you want to decode the created employee okay we are doing this decoding because as you know go line does not understand json so we have decoded that into a created empire right the whole json that we just received from mongodb and now you want to send that json as response to the front end so you'll say return c dot status 201 dot json by the way 200 201 203 400 500 these are standard uh you know statuses uh http statuses you can read more about them in case you don't know which status is used when so you'll send the graded employee make sense now um i've actually used insertion result here so let me make sure if this is the same spelling i've used here here's the scenes wearing now uh a lot of these packages have these quick lines so what i need to do obviously is i need to say so it gets all those mongodb and driver options since i have not done that for quite some time now and if i go ahead and save it it removes one package on which package it did remove any let me actually um so yeah just save it actually for now and you can see that all the issues have gone away right we don't have any issues now now we want to work on our uh put function but let me first check if everything looks fine with the post function if there's no big thing that we're missing as of now yeah everything seems to be all right so now we want to work on our put function put is basically your update and then you have at the end you have delete so i'll just create some space here just for some you know uh clarity and here as soon as somebody hits this route you want to call a function you want to call the function and this function is going to take c which is of type fiber dot cdx returns an error yeah now the thing with ids is that you get them very easily you can access them pretty easily using the c which is the context c dot params so the parents will have the parameter which is id that you just passed and i'll capture this in a variable called id param and also i will create it uh from hex so i'll say primitive the primitive package that we're using let's say object id from x id parent and i'll store that in employee id variable or we'll get an error so either it'll get converted or we'll get an error so it's giving us quickly line for primitive that means yeah so that means when i saved it last time i did remove the primitive package here so i'll copy this paste it here and i'll stay slash all right showing me three issues in the file i know there are two issues from here because these two we have defined but we have not yet used anyhow so now we'll we'll go forward we'll handle this error that we might receive here so if error is more equal to nil you want to return c dot send status 400 okay and just like you did with post right so update apis are usually very similar to the post apis so just like you defined a variable called employee and it was of type struct which is employee start similarly we'll have it here right and similarly the data you need to get from the body parser and you want to get it into this variable called employee so very similar so you will define a variable called employees of type employee and you can define a variable like like i said you know where employee employee or you can just say is equal to new implied there's two ways to define a variable in golang many more but uh these two are the most most widely used so here you'll say c dot body parser and employee just like you did in the post api and you'll handle the error here error not three are ours just two hours if error is equal to less than error or equal to nil then you'll return c dot status 400 dot send string err dot header now i'm going to start building up the query okay so because uh why do we want to build the query because uh the id that we've just received in this api right from the request for that id we need to find the exact record in the database and then with this new data that we've received to update we want to update or replace that data with this new data make sense so first we need to find the data for that id how do you do that you create a query you say based on d and you'll say key is underscore id comma value is employee id that you just defined out here okay then you'll say bsn.d and now what you want to do is you want to build the update quit how do you build the update query you uh want to have so when you do an update query right you have to have dollars set as in set this new data for instead of the old data so in case you already are familiar with mongodb will be very easy for you to understand if you're new to mongodb just remember that dollar set is the operator that you have to use inside mongodb to set this data for the data that you are replacing so this is how it's going to look like it's going to be sunday inside that you'll have a key and the key will be dollar set like i just mentioned comma there will be a value for that and the value is defined like this this one dot d inside that you have three things you have three things inside here a few things about the three fields to it one is the name comma value employee dot name and here you'll have key h comma value and employee dot h then you have k salary comma value employee dot salary makes sense here you'll just put a comma here and then here also you put a comma so now that you've built this query you to capture this and read it in this variable called update now you can see all the squiggling score went away quickly and you want to write the update function so the function update function that you get with mongodb is called find one and update so let's say find one and update you pass c dot context in you pass the query and when i say query i mean this query that i just created with the id so you find that video with the id and the update basically is the query where you set the new data for that particular id right so you pass query and you pass update both of these things you say dot err here and where you want to run this you want to run this very similar to what you've done before right you want to run this query in the instance like this the instance that you have right among instance which is mg dot database dot um collection just like you did here with your app.get right so the same thing you want to write here you want to say mg dot tv dot collection inside that collection will say employees right and error is equal to all of this now you'll handle the error so guys i just need some uh energy drink because i'm getting you know it's a long video if you don't mind all right so if error is not equal to nil that means that the filter did not match any documents so you want to say if error is equal to dot there are no documents right so there's an error and an error is that mongodb does not have those documents then you're going to return c dot send status 400. so 400 status you mean you know it's for not found that means whatever id that you're trying to find and replace the data for it does not even exist so there's something wrong so that's what you'll do otherwise if there's a regular normal error then you just want to return 500 all right and uh you want to set the employee id so inside employee dot id is equal to id param and uh if everything has gone well you want to send 200 saying everything is okay you want to send the employee so let's say return c dot status 200 dot json and employee cool now the only function that's that we're left with is uh the app.delete function but you may have realized that till now we have not actually started our server right we've not done anything to start our server so to start our server we'll just have to do just this app.listen on port 3000 and if there's an error you want to enclose this whole thing and you want to say log.fatal so if the star server does not start you do some issue like the port is already taken or there's some other issue we'll just basically be able to log out that fatal error now you want to start building the delete function the process is very similar you want to as soon as somebody hits this route or api you want to call this function which accepts c you'll have fiber dot ctx and it returns an error inside that you'll have now you obviously want access to the id right which is inside parents so it says c dot params inside that you have your id and you want to enclose this whole thing into object id from hex and let's say bring the dot so instead of doing those those two steps that we did earlier like perimeter object id from hex id param and then doing this we have done both of those things in just one step so if i did this earlier in one step you would have been confused so this is why i showed you how to do it in two steps and now how you can do it in actually just one step and you get access to employee id directly this means you don't have to do all this part with id param and then employee right you directly got access to the employee id anyhow now you can handle this error so you'll say if error is not equal to you'll return c dot send status 400. that means that probably the id that you got here is not valid so that's why we'll say it's not found 400. now uh what you want to do is you want to find the record with that id and you want to delete that record okay how do you do that you will first have to always like you've been doing till now you have to build a query because mongodb understands queries and the queries are in psalm format and this is what the query looks like it has a key and this key we're going to pass the id has a value and the value is employee id okay so it has a keyhander value and i've put a double quote here by mistake so that's why everything looks off you know it's kind of fixed and now i want to do the same thing i want to call the delete one function but where how do i get access to the defunct function i have to access the instance i'll have to access the database i'd have to access my collection the collection is called employees and inside delete one you're going to pass context comma ampersand query just make sure the spelling of context is correct and whatever you get back from this right from running this query whenever we get back you stored in result or you get back an error and you can handle the error now if error is not equal to nil then you return status um service internal server editor so let's say return c dot send status 500 and if the result is dot deleted the count is less than one so that means if it didn't get deleted then you want to return c dot send status folder for not found yeah so gonna say you wanna say that's basically not found okay uh if uh nothing got deleted or if the related count is less than one so obviously that means there was no um record like that i think uh earlier by mistake i said did i say somewhere that 400 is for not found sorry uh my bad it's actually 404 uh that's not found i got confused for 400 here's your other type of server error all right and here now if the record gets deleted so you want to say c dot status 200 dot json record deleted okay and that's your entire delete function so in about 16 8 169 lines you are able to write the entire program things look good to me and now i think we should start um testing it out and start seeing if everything works all right so what you want to do now is you want to head over to your terminal not this one sorry this one and you want to say go build main dot code now what happens is you see this main.exe file right so and since i'm using windows it creates a dot exe file for me which is an executable file and uh that's what build does it creates a build builds a exe file for you and what you want to do is you want to now run this program which is recorded let's see if it works okay so we get some uh issue here so let's try and fix things fixing it so we've received this error right and what do you make of this it says there's something to do with mango driver mongodb client right so it's quite apparent that something has gone wrong with and if i go to my code and i see that the drivers look fine to me and i know the code that i've written is quite all right and the only mistake that i see right now is with obviously is that i've not put a slash here at the end and maybe when it's trying to add this with the database name uh the whole thing is kind of fading maybe right that's my hypothesis and i save it and i run it again and i'll have to build it obviously first and then i'll run it again if you don't build it sometimes it runs the old uh executable file so just build it and now i can see that it's running the program so that was the mistake right so uh with golang you don't have to be a genius to solve errors so that's why i am very comfortable writing a lot of code and not testing it again again with other languages right you have seen other like instructors they have to keep showing you how just build a small part of the code and then they test and check check it out if it's working or not with golang you don't have to do it just write everything all at once and then easily you can debug it you don't have to be a genius we will tell you the exact issue where the issue is right anyhow so it says uh fiber is working on port 3000 there are five handlers processors is one pids to one three zero all right so now you head over to your postman and you come here i've created a collection set of collections so get all employees which is basically localhost 3000 slash employee and i get all the employees i that i have and right now it's saying that i have zero employees right it's an empty added obviously we have uh no employees that means i'll start creating employees so firstly i'll create an employee caller that's created so it's created it for me i'll create another employee called rupert uh now i see that there's another issue there's a duplicate key error issue okay so this means there's something wrong happening with our id and i kind of suspected that when i was reading it didn't send didn't show me an id that means there was something wrong there as well so now let me try and fix this id issue back in our code in the post function everything looks all right to me that means there could be some issue here yes now i see the issue there's just one small space between id and omit empty so let's remove that and now i think it'll work because this format that i had gone for it probably mongodb did not understand it so let's cancel our process buildmain.gov and runway.go and now i'll allow access on my firewall and so let's try adding some employees let's try adding robert cool you get an id here now and you add alex right so you're getting these ids here you get all employees and you'll see so many employees right now what you'll do is you want to edit an employee so let's edit rupert so i'll take this id go to edit employee just see that it's local 3000 slash employee slash the id of the employee so the id of the employees are what i want to replace and i wanna and i can send any data here that i want i'll change his name to peter when i do that rupert's name has been changed to peter so if i get all employees that second rupert has been competed but this first and third rupert are always still there but the second rupert has now become peter okay you want to delete an employee now so you just copy and paste his id again for delete employee when you paste it here send record deleted now when you get all employees you'll see that peter is not there so the first rupert is there second looper is there and peter can't be found so you can see that right the issue that we were having earlier was that id was not being generated for the first record and if i was trying to add more records i was saying that that same idea already exists so it's an error for mongodb but now the ids are being generated because i removed that small space so all the apis are working perfectly here's your little human resource management system you can create employees delete uh and updated employees you have learned how to work with go fiber which is a very nice library learn how to uh connect a program which uses go fiber with mongodb it's a complete serverless stack right so you're using dynamodb serverless you're using lambda serverless again and then we'll be using api gateway again serverless now api gateway helps us uh enables anybody across the world to interact with our lambda function right so we'll be deploying all these three things uh from the aws console right we'll be using the aws console and then we'll make settings for all these three things and we'll deploy all of this and anybody across the world can use our lambda function so this is more like a real world scenario so i'm in my terminal now and you don't really have to keep this project in your go root because since golang 1.12 anyways they had you know go mod in it which we're going to do anyways out here go modern it takes care of everything i mean you don't have to really uh do anything manually all right so here we'll say we will make a directory first we'll say go serverless and yt all right and we'll see into this go serverless stack yt for yt is basically youtube i'm making this project for youtube specifically all right and here i'll say um go mod in it and which is basically github dot com slash akil slash go serverless yt so that's my project it's initialized go mod for me go mod is basically like my package.json file if you're from a javascript background it'll have all my dependencies for me you know easily listed out so um now what i can do is i can just open this project up and code editor which is vs code in my case um just as a pointer right i'm using windows inside windows i'm i have something called as wsl inside that i'm using ubuntu 20.04 and i use multiple different versions of ubuntu right and this for this particular video i'm using ubuntu 20.04 and in my ubuntu 20.04 uh instance i have vs code set up all right now uh i don't want to install a lot of extensions uh for golang because i know when i'll start typing uh i'll start writing a lot of code i'll make some mistakes right with golang i'll make some mistakes but i will fix them so don't worry i don't have extensions because i don't want to like start uh you know ballooning up my instance because this is just one of the instances that i use uh on my windows pc for ubuntu i have like 10 15 different versions of ubuntu right so uh if you new to golang by the way main.go file is your main file right in the project and this is how you start domain.go file you say package main and you say import and because you'll import some packages right not everything you'll have inside golang golang is very modular uh you have to install a lot of external packages and a lot of uh you know packages that come with golang you have to specifically tell that you know i need this package from coolant and uh so the the third party packages that we'll be using will be mostly around lambda all right so we'll talk about them in a while and then uh the most important thing here will always be funk main because that's your entry point into the program right the funk main uh now before i start writing anything in main.go file what i'll do is i'll just try and create like a very simple project structure i need the build folder right because i'm going to keep my build of this entire project in my build folder and that's i'm going to zip it up and then i'm going to keep take that zip file to my lambda uh sorry my aws lambda console all right so that's why i need the build folder and i need my cmd folder because that's where i usually keep my main dot go sorry not in the build but in my cmd folder i use keep my main.co file all right and then you'll have a package folder so uh if you've worked with golang before this is like the very standard kind of uh structure right nothing nothing new so package will as you already know will have handlers right handlers to handle the apis and then you will have i'll have a folder for user i'll explain to you why i'm doing that and then i'll have a very simple validation function so i'll keep that in a folder called validator write daters sorry uh that's it yeah so in validators i will have just one little file of badly like five six lines of code i think it's just going to be as email valid just to check if my email is valid for the user and here in my user i'll have a file called user.go all right and my handlers that's where my main logic resides so this is a very short very small project handlers i'll just have two files i'll have api response dot go because i need this uh file for uh my api gateway i'll build it you'll understand what it is and then it's handlers.go right now my user.go file is kind of a combination of my models and my almost like my controllers as well you know so i have handlers uh but you know user.go file will have a lot of code which kind of which talks to my database all right directly talks to my database so i'll have those models like those structs as well at the same time i'll have model functions uh those uh sorry database functions at the same time i'll head over to your main.co file in funk main i think what i'll do is i'll start with this place right i'll say os dot get environment pws region so aws region is very important because that's where your uh lambda will go and sit right so with aws if if you've worked with aws a lot you know that it has different regions right so my particular aws is configured with india which is asia pacific south once uh if you have uh been using cli and it's set up it's uh it'll be amazing uh otherwise also i don't think you should have a problem right but just try and uh just try and set up awcli it's very easy it's just a five minute process and it will be very simple for you to follow along with all of my other videos as well because uh in my other videos it's a prerequisite so um how do you create a session so you'll say session dot new session now if i'm calling this os here right so i need to have os here that's the package right and if i'm calling session here session is something that aws lambda gives me aws gives me sorry so i'll say github dot com slash now i'm looking at the documentation for the aws packages at the same time you can do that otherwise in case you're you're the type of person who wants to like know uh exactly which package you are installing because i am that type of person i don't want to install any extra packages right so if you like me you you might want to open up um just like i've done you might want to open up the aws sdk it's called so i'll say aws aws sdk for go you want to you want to open up the documentation and here you'll see it will be slash session all right and to create the new session you'll see aws dot config and the bracket which will be curly braces bracket you'll say region aws dot string inside that you'll pass the region all right all right and then as you know with all everything to do with golang whenever we haven't uh we get two things usually right we get the thing that we're looking for which is the aws session which will come from the session function right sorry the new session function which is a part of the session package that we have here and we get the error so with golang you have to like keep handling errors and this is a very neat and clean way of handling errors because at every stage you know where there is coming from and you can handle it there itself so if there's an error just return all right and i want to create a variable called dynaclient which for my dynamodb and dot new and uh how do you create a new client you'll say aws session perfect which you've just created out here so you've created the session and then you'll say lambda.start and handler so this you may not understand right now not a problem so firstly we want dynamodb how do you get dynamodb you get it like this it'll say github.com aws slash aws sdk go slash service slash dynamo db all right so you have session you have dynamodb and you want aws itself in the first place so you'll say github.com slash aws sdk go slash eight plus to get this lambda function uh sorry the lambda package which has the start function you need the start function what you'll do is you'll say github dot com slash aws aws lambda go slash lambda cool so far so good that's what i needed you know and i need something called as the handler which we'll talk about in a while okay for now i am creating a constant called table name stable name is lambda user i'll say lambda in go user and now it's time to create my handler which is this basically so i'm passing my handler there in my handler what i'm doing is i have a request basically i accept some things right in this function and i turn some things and it has some definition so what does it accept except accepts events dot api gateway proxy request so you're wondering what's events right so events is basically what uh golang lambda will give us so i'll come here and i'll say github.com slash aws aws lambda go slash events perfect and the other thing that this accepts is star events dot api okay to a proxy response sorry i meant that this it accepts a request returns a response i'm not sure what i said actually before that what i'm trying to say here is that you know this is a function that accepts something and it turns something obviously accepts a request obviously returns a response right no complication there that's what you wanted to do and what you'll do here is you'll switch uh with the http method so you'll say switch we'll say request dot http method so what are the htm methods that you have you have get post put and delete that's all you have so for every single different uh hb method you want to call a different function how do you do that so you'll say switch sorry we've already switched right we've already switched uh it's like um it's 8 30 here some kind of sleepy uh i usually get sleepy at 11 pm but somehow today i'm sleepy earlier because i woke up really early i have joined this martial arts class that that you know gets me to wake up at 5 00 am these days so so you'll have something called as handlers right and where will those handlers come in from it's basically these handlers that you want to import so which are basically your own uh creation your you know the handlers are your own creations you'll say github.com handlers cool so you're saying to go lank is that uh this is my project github.com go serverless yt inside that i have a folder called package instead of a package called handlers right and handlers the file uh on top of that file will say package handlers and it belongs to the handlers folder then golang understands okay that this is what we're talking about all right that's the format i mean the the folder name and the package name have to be the same just letting you know in case you didn't know that i mean um i mean i'm pretty sure you knew that but i'm just making sure right so you have request table name and diana client right so you send this to this function called handlers.getuser which we'll work on in a while so that was your case get now you have more cases right you have depending on the http method so you have post you will have put and you'll have delete post you'll set it on handlers.create user again you'll pass request comma table name comma dyna client for put you'll pass return handlers dot update user request comma sorry request comma table name comma dinoclient and for delete we'll just do handlers dot delete user and same things you'll pass the same things comma dyna client and after delete you will just give it a default if you work with case search and case statements you obviously know there's a default right and try to keep the identitation same it won't affect it but just it's just a good habit you know i mean i don't do it many times but you know i try to do it these days all right so by default you want to call this function called unhandled method which is again in your handlers file or handlers package and this is the entire picture i mean uh i don't think we're missing anything we have the os package down here we have events lambda aws session dynamodb yeah there's one more package actually if you look at the aws sdk document then you want to import h sdk go slash service slash dynamodb slash dynamo dvi face just keep these packages and what i think we should do is we should just say go mod diary so i'll get us all the package that we've just uh talked about and usually like many times i do this at the end of the end of the video right but this time i'm just doing it beforehand itself because many people they can start freaking out hey you're you're installing all these packages if not you've not run the command go my go mod id or you're making so many mistakes man while typing why don't you install some extensions i've explained to you why i don't install extensions right so so with golang i mean what happens is that you know we usually come from javascript kind of a background and then we think that oh you know if you're making all these mistakes then the complete program will crash and uh it will be difficult to solve it but with golang golang is very different from other programming languages right make as many mistakes as you want and once you run the program golang will really handle everything for you it'll tell you which line what's the problem it's quite intelligent right it's not like your regular uh other programming languages like javascript so here one thing that we missed out was to create the dyna client in the first place right so the then a client has in the variable and defining the type of variable the dyna client is so what type of dynam uh there it will be that's where we'll use this thermodb i face right we'll say dot dynamo thermodv api just make sure you get this right all right so that's your main file your main file is complete and now you want to start handling handlers so here so since these two files belong to the same folder called handlers we want it to both to be package handlers right so we'll say package handlers right that's clear till now i'm hoping and after writing the package you say import and then you have your main func you know for in this case this the main function of this file is called api response accepts some things return some things and has a function definition what does it accept accepts status which is end and body which has an interface what does it return it returns event start api gateway proxy proxyresponse comma error right for importing you will say encoding slash json and github.com slash aws slash address lambda go slash events okay all we're doing with this is basically defining the response right so we'll say response is equal to event start api gateway response the response you're just setting the headers pretty standard because the way we're going to set up these headers are something that you've already seen so many times which is basically content type and application json so we're saying that we're returning json from our lambda function right nothing uh out of the ordinary so we'll say response dot status code is equal to status and so i will be basically your like 400 for 300 uh something like that and then you'll say string body comma json.marshall sorry so you are uh if you've been with golang you already know what's matchling and d marshalling unmarshalling sorry is golang doesn't understand json on its own so it needs the help of json marshalling which is part of this encoding slash json package and uh yeah so whenever you send some json from postman into um postman or maybe terminal wherever you send some uh json uh it basically we we want uh golang to understand it also and also the information that golang produces for it to become json uh and send it as a response that also needs uh you know help a goal i need help with both so that's why it's called mastering and muscling there are hundreds of videos about it on youtube you can check it out nothing fancy or nothing complicated you have to do that in uh you know almost all the other languages right which are not javascript which is like basically java and python all these languages you have to do something like that right because any language that's not javascript does not understand json by default because json is javascript object notation so this is your api response dot go all right that's it i mean there's nothing much going on here in this file but the other file in handler's package handlers this is where we're going to spend some time because obviously there will be a lot going on here right uh so the main functions that usually will be there will be based on our main.go file so main.go file requires get user function create user update user delete user and unlock method unhandled method sorry so these are the functions that obviously that you need to create right so you say get user and you'll say create user you will say update user and delete users func update user and delete user alright so here the last function that we want to keep here is unhandled method right so for let's say if somebody uh uses the patch method because you're handling get post put delete if somebody uses batch then we'll say that hey it's not handled right so we'll say unhandled method accept some things return some things and has a function definition all right so this is uh in general this is how your handlers file is going to be like and what we can do is we can work on our is email validated uh valid file so we'll say package validators and there's a package that you get with golang it's called regular expressions and we're just creating a simple function where we're just saying if the email is valid or not right really simple all it does is accepts an email string and returns a boolean like yeah true or false we'll take a variable called rxemail we'll use the reg expression regular expression package and if you look at the regular expression documentation like i have in front of me go to the golang official documentation and check out the regular expression package um i i highly recommend you to open it if you want because that's what i've done out here in my other screen we'll use the function called must compile and i'm going to copy and paste a regular expression string here you don't really need to understand what this does you just get it directly from the documentation but if you really want to know basically uh you're just checking if you know the numbers are between a to z a to z and zero to nine that kind of stuff right that's all it's doing and it's also checking for at symbol right that means obviously if it's an email it needs to have an ad right so those kind of things just basic email validation check is happening out there do check out the regular expression document if you want to really understand what this regular expression does all right but if you want to save time just copy and paste it like i did just did and now we want to check the length of email female if length of females less than three or length of email is more than 254 or our rx email variable dot mat string then you'll just return false right so this returns either true or false if these conditions are not met then you return false otherwise you return true that means everything is fine and email is valid right obviously if this is not uh proper it's not working properly if uh length is more length is less we'll say the email is not valid otherwise we'll say it's true you can change these numbers as you want but i've kept them to be 3 and 254. all right you can change it on your taste so uh now we'll go to our user.go file and we'll just add a very 10 000 feet level i'll just set up this file now what i want uh should happen is that from my handlers like the main control you know that will go to the main file to our uh you know to this function basically and this function is calling the get user function and create user function update user and all these functions are as you know mentioned in the handlers right and from the handlers from the handlers you'll call the functions in your user.go file and these functions will be actually the database functions that actually talk to the database right so every function that you have here except for the unhandled method because it doesn't do much uh these four crud functions that we have they have an equivalent function in your user.go file a complete like one is to one function in your user.go file that talks to the database all right so let's do that let's create those functions so firstly as you know when we start off a file we import some things and then here i also want to find some variables some errors that i want to define so the functions that i want to have here in my user.google file which will have one is to one relationship with these four functions the first function will be called i'll call it fetch user so that means is uh my get user function gets called in my handlers and this function will call in my user.go file the fetch user function which directly gets uh the user from the database itself the database in this case being dynamodb right so it accepts some things returns some things and it has a function definition simple the second function that i want to have is for getting multiple users actually so i'll say funk fetch users similarly it'll look very similar then i want to have a create function so i'll have create user and then it has update user okay you just have to keep looking here and then creating these functions and then you have the last one is delete user right so you'll come here right if it doesn't get deleted then you don't have to return anything specific so especially you can just return an error that's why from the return here is just an error right and that's about it so we have one into one functions all of these but one extra function is there which is fetch users all right so we'll see where to get where to use it so from a 10 000 feet perspective this is your user.google file and this is your handlers file so what we'll do is we'll start working on our handlers function and then at the same time we'll start working on our uh user.go functions and here you'll obviously import some things right um the first thing that i need is net slash http then i need my lambda event so i'll say github.com aws lambda go slash events now it's possible that i'm importing these but you're not understanding why i'm importing these so you might get confused so uh now there are two ways to do it one is when i'm actually writing the code and then i use this events packet somewhere and then i come and come up and you know import it or i know um you know which ones i need so i'll just import them right in the beginning itself so that i can use them later on so i'm just doing this so try not to get confused because we'll actually be using these packages in just like two three minutes don't worry you know why we're importing them where will we use it so please be patient slash aws right so these are the same packages that we already use in our main.co file and we'll say github.com slash aws slashing plus okay go slash service slash turnover db slash dynamo tv i face great one thing that i need here because i would want to call these functions like i told you right i won't call these functions so that's why i want to import this user package in my handlers file how would i do that i would say github dot com slash a kill slash go serverless writing slash package slash user so inside package inside the user package we've imported it here all right and then before i get started these functions i want to define a very a variable called error method not allowed is equal to method not allowed and why do i need to create this because firstly we'll be working on this function unhandled method right so that's why we want to call this function so here this returns an event api gateway event so it will say api gateway proxy response comma error right so we'll just send response from here or we'll just send an error and here you'll say return api response the response that you want to send is http dot when we say http we are talking about the http package net http package all right status method not allowed comma header method not load which we have just defined together right that's what you're saying so we're saying that uh we have uh you know something for get post but complete but we don't have something for patch so patch or any other method that somebody uh plans to use so if you get something like that like an unhandled handle method so you'll send a response saying that hey this method is not allowed all right and i want to create another variable but it's actually a struct right so it's an error body and i'll be using it a lot so just bear with me as to why i'm creating it this struct has a variable called error message chat string error comma commit empty cool now for your get user you have you accept something and you turn something here for a get user what do you accept what do you what does the function get you get a request right from postman the request that you get is um part of this events packet so you'll say event start api gateway request comma table name which is string comma diana client dot dynamo db api and what is return it returns a response obviously so we'll say events dot api gateway proxy proxyresponse comma error straightforward and actually this these two things right well it's going to accept what's going to return it's going to be used by all of the functions so what you'll do is you just copy and you'll just paste it here for create user for update user as well and for delete user as well awesome so we've done a lot of heavy lifting now we want to start working on the function definitions for these all these functions right so the first thing that you'll say is email request dot query string parameters email so if you've guessed what's happening here is you want to get the user but by using the email id of that user so from a request you'll have your query string parameters which we'll pass as email and that we're going to capture in a variable called email and then we'll check the length so we'll say if length of email is greater than zero then you'll get a single user so you'll say user dot fetch user which we've just created together right we've not created the definition but you know which function i'm talking about it's in my user uh package which have been imported here already so fetch user is going to take the email table name and die in a client and i'm going to capture this in the result or they're going there's going to be an error and if there's an error i'll handle the error so i'll say f error not equal to nil return api response http dot status bad request comma error body so error body is a struct that i've already defined and in error body i want to pass aws dot string error dot error and otherwise you'll see hdb dot everything is okay so we'll say status okay if everything goes well and you'll pass the result from this function now if um if you want multiple users you'll say user dot fetch users same thing table name and a client and what you'll do is you'll again use result and error to capture the values coming from this function and if there's an error and you'll check if error is not equal to nil you'll return the api response saying http.statuspad request because there's an error right and you'll send the error body just like we did earlier error body is the struct that we've already defined that's the error body that we are sending which is basically json and here the error body uh inside that we're going to send you're going to send aws.string header dot error got it but if everything went well and there was no error then we're going to return api response and http dot status okay comma result so basically that's your get user now what you can do is we can work on our fetch user and fetch users both of these functions in our user.go file or we can work on our create user function in our handlers so i think i'll do the former i'll work on fetch users and i'll work on fetch user let me just check if everything is recording yes everything is recording perfectly and i just i need to keep making sure otherwise you know i end up making a long video when nothing has recorded and that leads to a big problem all right so before i do anything with users i want to first create a user right so like i said this file is a mix of that model file that you usually create where you define the struct of how the user is going to look like so i'll say user struct email now since this user struct is small and we don't have multiple structs like if this was a um e-commerce for example then you would have had users and orders and you know all those different like products and so many different structs right so you'd have to have like a model separate models folder for all these different models and then you'll have you'd have you know database functions separately and controllers or something like that right but since we don't have that we have a very small project which just has users and users all itself it's a very small struct because you just have email first name and last name you don't have too much here right you can combine controllers and models into the same file now email is going to be a string which is going to say json and you say like this json email because for golang's purposes it'll be emailed with a capital e whereas when json where it's stored uh it's going to be emailed with a small e so you need to tell golang that you know there are two versions of it one the json version the another here's the version that golang understands because golang does not understand json as i've already told you so that's why we'll also you have to use some marshalling and unmarshalling uh to get it to understand and interact with json all right so you'll have first name and last name and then what we'll do is we'll create our fetch user function what does it accept so if you actually go to handlers you'll see the fetch user function accepts email table name dynaclient so we'll say here email and table name which is string and your dyna client which is of type you already know that more dbi face dot dynamodb api and it just returns a user obviously i mean you fetch user you return that particular user or you turn error if nothing works out you define a variable called input and it's of type dynamodb dot get item input so we'll have to define the key based on which our database function will run to find that particular user and you already know that the user will be found from the database based on the email id so we take an email id we're taking an email id and then we want to find the user that's associated with that email id all right so straightforward we'll say dynamodb dot attribute value and we're going to say email because we want to run a query on email so email is equal to s is equal to aws.string dot sorry inside that bracket will pass email now the string is a function that is given to us by aws package aws packet is something that we'll have to import out here all right uh and similarly with the dyno db so we'll have to also import the dynamodb package so come here on your import and uh firstly called encoding json because like i told you golang does not instant json by default so you need uh encoding slash json package to uh use the marshalling and unmarshalling functions and i need the errors package also then i want to uh get my hands on the events and i'll be using it soon to send responses and the usual ones uh as you can see i need dynamdb and i need aws so let's get those ones so i'll say aws slash aws sdk go slash aws and i'll say github.com aws slash aws sdk go slash dynamo tv um and what i'll also do i'll also get this particular package um yeah let me do that for now so i'll say github.com aws slash aws hd case go slash service slash dynamo db slash dynamodb i face all right now coming here you've already passed this and after this bracket you need to specify the table name in which this function is going to run so we'll use the uw string function again to pass the table name and after this bracket you want to use your dyna client to finally start getting the item input is this basically the query that you created right and get item is the function that you get in a client and you will capture that in result and error so standard practice if there's an error we'll have to return the error so we'll return nil for the value and we'll return errors dot new error failed to fetch record so um you must be wondering where is where does this error come from you've probably never seen this error right because this is a new error that i've created on my own how can i create my own errors i can create my own errors like this so error fail to fetch record is equal to fail to fetch record and similarly i can define any errors that i want in this variable uh defined as a variable right so you've uh you know created a query very similar to mongodb write you've created a query based on the email because you want to search for that email so that you can retrieve the user and you've run the function get in get item for dynamodb and you've passed the query to it and you've received that in something called as result or you received an error so if there's an error you handle the error but if the result is fine and nothing really happened then you would do something right but before that we'll create a variable called item and it'll be basically a new user and here you'll say error is equal to dynamo db attribute dot on marshall map okay so dynamodb attribute is another uh by the way if you have not opened up the dyno db uh and aws sdk go documentation do that because i have it open on my other screen you can do that as well and then everything will make a lot more sense because these are actual packages inside that main package right so i'm using those and once you go through the documentation you'll understand where to use uh which one or you or if you really don't care about that you can just keep following along with what i'm doing but i just recommend that you just read it because you know everything will make more sense here i need this package right then would be attribute this is helping me unmarshalling the user so first let me write the whole code so i'll say result sorry not here here upper bracket will say result dot item comma item and this error if this error is not equal to nil what we want to do we want to return nil comma errors dot new error failed 2 on marshall record so you must be wondering what's happening here right so when you get the data from your dynamodb using the get item function into result you want to unmarshal that into an actual user which the front end can understand as a json basically so you use the user struct and you uh you know take that in a variable called item right so item is basically um a variable of type user and then uh you know you want the data that's coming from your result dot item you want that to be unmarshaled and brought into item so that now whatever has come as uh json uh becomes uh you know the type which is user which is understood by golang but and it's captured in a variable called item right um so i've tried to explain to you every single line in case you don't understand it do check out what's marshalling and unmarshalling all right and if you have any error like if you still have any confusions you can just put it in the comments below i'll sort it out for you but it's nothing very difficult right you're just um taking what's coming from dynamodb the json and you're unmargining it to uh make it into a struct right which is of type user which has email first name last name something that can be understood by golang and you're capturing that in a variable called item which is obviously of type user right that's stuck that we have defined this is standard practice i do this in all my other videos as well in case you're new to this channel i have hundreds of videos on golang you can check all of them out like literally hundreds of videos on go like right check them out build projects with me and you'll understand very everything very easily so if everything went well if there was an error obviously you sent nil and you sent the errors but if everything went well you would return the item and then you will return nil for the error now you'd want to also work on the fetch users function the plural fetch users function how do you do that you are passing table name there as you can see here you're passing table name and nano client so table name has been passed which is obviously your type string you passed denmark dyna client which is of type you already know dynamo dpi face dot dynamodb api and you return multiple users how do you run multiple users you return basically a slice of users wherein users is the struct that you've defined right so you're using a struct you're making a slice of all those users and then that's what you're returning i hope that makes sense if you don't know basics of like of course like slices and structs then i highly recommend you check out the basic tutorials before uh you get more confused so um i want to use a function but that dynamic db gives me it's called scan input to get access to table name which is aws dot string and table name that we are already passing here got it and you will say dynaclient dot scan and you want to scan the input the query that you just created right so here as you saw uh we had a more elaborate query because we had to get a particular user with email but with fetch users you're just getting all the users you don't have a specific query that okay you know for this email i get a particular user saying get me all the users so you don't have any query as such you're just passing the table name so that's when your dynaclient.scan you just pass the input that's it and scan is like get all you know you can say that so if you've used uh that mongodb it's you have find find all something like that here you just have scan find and find one you have in mongodb so you just have scan all right scan and get item so you're doing scan to get all the results and you're going to capture that in a variable called result and then you'll obviously if you have an error you know that standard way to handle errors is like this you'll say return nail for the value and you'll return an error so you'll say errors dot new error failed to fetch record and again like we did out here item we'll define an item right the item here is not just a user it's a slice of users multiple users because we're getting all the users from our database and again the same thing that we've just done here we'll do the same thing here so we'll say error is equal to just copy the whole thing actually copy and paste but there's only one small little change instead of result.item you'll have result dot items because obviously from your database you'll get multiple items multiple users that's what you're getting and you're returning your item and for the error you're turning nil makes sense so we've done quite a bit right we've already done the get user function and get user function had fetch user and fetch users two functions from your user.com file now there are three functions left here and three functions left here because we've already taken care of the unhandled method function you don't have to do anything more here so just three functions left here three functions left here and all the other files are kind of complete right so if you've reached this far congratulate yourself because you've come you've come a long way right um so now let's start thinking about how our create user function is going to work all right so for the create user function let's let's start building that there's actually not much happening there all these functions right uh create user update user delegator they're all going to look very very similar so i'm going to say user because you know uh you want to call the create user function the user package so you'll see user dot create user which is this function that's what you're calling right and you're passing it three things request table name and a client make sense now whatever response this function returns you want to capture that in a variable called error sorry result and you'll get an error which will be captured in error and you know the process from here if there's an error which means error not equal to nil you'll return api response http dot status bad request comma error body and what will be in the other body everybody in this case by the way is sorry the struct that we've already defined right so what's there in the everybody it's aws.string with a single r sorry string err dot error and comma okay and you'll return api response http dot status created comma result so if that means if there is no error everything goes well then you'll say hdb.status created all right and that's about it that's it actually that's your create user function there's nothing more to it all right and then for your update user function very similar you'll obviously call the user just like you did here user dot create user here you'll call user dot update user method so you'll see update user and you'll pass three things request table name and dyna client and you'll capture that in result comma error and then you'll check again if error is not equal to nil you'll return an api response http dot again status bad request comma error body inside the other body again the same thing it resource string error dot error all right but if everything went well if the user did get updated then you'll return api response and you'll say http dot status okay that everything went well and you'll return the result so that means what's happening in these two functions create user update user is that these two functions are being called that means a lot of the logic the main logic is going to happen in these two functions right because not much happened in the in the handlers similarly let's work on our delete user function here you'll say user dot read user you'll say request comma table name comma diana client here also though the only thing you'll run from here is the error right if the user didn't get deleted you'll return the error you don't need to return the result any result from the delete function so if the result is not equal to nil you'll return api response it you know by now what we're going to say we're going to say status bad request and we're going to also send the error body which will have aws.string and the error itself but if everything went well you would want to return the response with status ok and ultra nil for the error okay so that's um that's about it and um yeah that's it i think the entire file is complete now we don't have anything else to do i've also gone through the aws uh sdk documentation i don't think anything else need to be done in the handler so everything looks all right to me uh and now we'll have to work on our uh user.go file and all these different functions that exist on our user.com file for your create user function what all it's going to accept depends on what you're sending from here which is requestable and nanoclient so here you'll say request event start api gateway proxy request comma table name which will be string and data client which will be you already know then mdbi face dot nano db api so what is it going to return it's going to return the user that has been just created or an error so here the first thing that we'll do is we'll create a variable u which is of type user user being the struct that we will define that means you will have email first name and last name all right so let's start from there now we'll use u why did we create this variable u it's because we want to capture what's coming from postman so from postman or from let's say the terminal wherever we'll send the json of the user with the email first name and last name and that data needs to be unmarshaled into you so that golang is able to understand it and also perform any operations on it so what you want to do is we want to use the json encoding json package to call the unmarshall function and what you want to do is you want to pass the request dot body to it comma ampersand u if error is not equal to nil and also here we'll fold the right syntax for the if statement and if error is not equivalent then we'll return nil and we'll return something for the errors we'll say error invalid user data but we don't have this error here right so we don't have uh this error error fail to and marshall record we don't have error in values of data we just have error field to fetch record that's all we have defined so now let's define all the other errors let me define all the other errors that i'll need in this entire file in the beginning itself so we'll say error failed to unmarshal record is equal to fail to unmarshal record an error run and i'll add error and valid user data is equal to invalid user data invalid email also will be there and valid email is equal to invalid email then we'll have good not marshall item and could not delete item so then we'll have could not put item so we'll say error could not dynamo put item is equal to code not dynamo put item and user already exists user does not exist user.user does not exist so why do i need all these errors obviously by now you would have understood i'll just give you an example that uh when creating a user right if we check if that user already exists then we don't need to create that user so that's why we need this kind of an error and if you want if you're updating a user then or deleting a user we can use this that user does not exist so why are you trying to update that user right that's why um i'm just thinking about all the type of error functions i'll need error statements i'll need so depending on that i've just created them so coming back to your create user right here now we will start validating uh the email so we'll say validators dot validators is the package that we have created together right this one and the function that we created in that package was is email valid and you is the variable that you defined and now after unmarshaling the request that you uh in the body body is of the request that you got from let's say postman or from the terminal as json you captured that in you so now you can now golang can easily understand you because it's unmarked right it's not json anymore so you can access u.e mail and you can run the validation function on it so here the spelling is wrong so it should have been is email valid and you'll return nil errors dot new error invalid email right and now the reason why i created this uh error is because i want to see if that user already exists right so if that user already exists then you don't need to create it so we need to throw an error so we'll check if the user already exists right so i won't put that comment actually i was just trying to show you so to check if the user actually exists you have to run the fetch user function you will say u dot email comma table name comma diana client and you'll capture whatever comes from this function in current user and we won't handle the error so i'll put a blank there so if current user is not equal that means there is this user exists right if current user is not equal to nil and length of current user dot email is not equal to zero then you return nil comma errors dot new error user already exists and so all of this if the user exists but if the user doesn't exist you will just save that user right so how do you save that so first to save that obviously uh whatever you now have in you you want to start um you want to start marshalling it right so that dynamodb can understand it now so you'll say dynamodb attribute dot marshall map you and you'll capture this in av and you'll check for the error so if there's an error we'll return nil and errors dot new error could not marshall item which we've already defined we've already defined this error right and now you want to start creating your um data that you will be sending to dynamodb so how would you do that you'll say dynamodb dot put item input item is av comma table name is aws dot string table name and finally you'll say dynaclient dot port item and you'll send this input that you've defined here so yes missed the is equal to sign by mistake similar to fetch users right you created this input and then you call the dyna client function similarly you're doing that the same thing here you're calling the put item function and you'll capture that in a blank character blank variable or and or you'll get an editor from here and if error is there then you'll just handle it very easily you'll say return l comma headers dot new error could not time output item right you've created this error already but if everything went well you just want to return the user awesome so this is your create user function and now you're left with update user and delete user everything else you have taken care of right the handlers.go file is complete api response is complete as as email validate is complete and main.go is complete and i think for our user file we have uh imported all the packages except for validators so you need validators so you'll say github.com the validators package that you've already created we talk i'm talking about that one so we'll say go serverless yt slash pkg slash validators let me also check what else am i missing for handlers i think i've already imported user and i don't need any more packages for api response um i don't need more packages for is email valid i don't need anything else my main.go file probably i might have missed something so it has handlers it has os events lambda aws session dynamodb dynamic dbi face so everything is proper based on the aws sdk go right check out this documentation you'll know why i'm importing these packages and how i've used these functions you already know that because you've been building it with me all right um then we'll come here again back to our user.com file and let's start working on the update user function so what does it accept accepts request which is of type events dot api gateway request comma table name which is string comma dyna client which is of type dynamodb i face dot dynamodb api returns a user the updated user and or i mean i mean r it sends back an error and we're going to do a lot of things which are going to be very similar to the create user function which is basically we create the user first we create the user right which is the variable u which is of type user and we're going to unmarshall just like we did uh we're going to unmarshall the request body that you get so request dot body comma ampersand you so by mistake um yeah so i have to close the bracket here because this is together and this is this variable u okay and here are not equal to nil if you don't want to follow along you can just copy and paste this part right i'm not copying and pasting because uh this syntax might be new to many people because it's dynamite kind of working with dynamodb so i'm uh writing everything by hand but if you want to copy and paste if you're very comfortable with dynamodb go ahead and do that you don't need to you know practice along with me then you want to fetch the user and see if that user even exists so you'll say u.e mail comma table name comma then a client and you want to capture that in current user and you want to check for that current user so if current user not equal to nil this is exactly what you did in the create function as well and length of current user dot email is equal to equal to zero then you'll return nil comma errors dot new error user does not exist so for the create user function we were checking uh for the user associated with that email because we wanted to see you know if that user only exists we don't want to add that user but for update we're doing the reverse we're checking for that user because only that user exists we can update the data for that user makes sense and exactly the same things we'll do because now we want to start so now that the user uh you know um if the user doesn't exist we'll throw an error but if the user exists then you want to start updating the table with the new data how do you do that whatever you've unmarshaled right now from json to you know unmarshalled to something that golang understands now you want to start marshaling it to something that animaldb understands so you already know what you want to use you want to use the marshall map function i want to pass you to it because you've just unmarshaled and which package is a part of so it's part of the dynamodb attribute package we'll capture it in a variable called av or we'll get an error and now we can easily handle the error so we'll if error not equal to nil return l comma errors dot new error could not martial item this one really really straightforward now you just want to create your input item and then you want to just call the dyna client function only two steps remaining so you'll say input is equal to ampersand dyna modb dot put item input and the item is equal to av comma the table name will be equal to aws dot string table name and the last thing is you'll use dyna client dot put item and you'll pass the input and if error not equal to nil nil comma errors dot new error could not dynam output item return ampersand u comma nil so now even my update function is complete everything looks okay and all i want to do now is um run the gomot id command to get all of the packages that are you know not there so i think it's taking a while i can't find my phone anyways so um while that's happening in the background we can start working on the delete user function so as you can see it's all installed i had a couple of issues actually um as you can see and most of the issues were because i had a couple of spelling mistakes here instead of sdk i did an skd you know so a small small few mistakes i had made just make sure you get these right um you can easily get them on aws sdk go um you know documentation or if i put mostly i'll put this code on github so you can just pick it up from there all right make sense just pick it up from there instead of typing it all yourself because i made a couple of mistakes so it was taking a while but now it's installed all these packages so in your user.go file everything works perfectly right like we don't know if it works perfectly but everything looks perfect to me and all the packages are in place all you need to do now is work on your read user function which is actually the most actually the like the easiest function so it takes request event start api gateway request comma table name which is of type string done a client which is a type already know you already know that dot dynamic api all right so what do you want to put in the function definition you want the email of the user right so request dot query string parameters and the parameters email then you'll create your input to the function which is of type dynamodb and dot delete item input item input star dynamodb dot attribute value basically you're passing the email and then finding the user and deleting that user with it associated to that particular email right nothing complicated so you'll say aws dot string and you pass email to that after this you'll say table name here ws dot string pass the table name and now that you have your input ready just like we've done all other functions you take the dyna client you call the dynamodb function which is delete item in this case and you pass the input to it input basically has your query for deletion which is the email id and you get the error and if there is an error you'll return errors dot new error could not delete item perfect otherwise you just return nil nothing basically that means that the user has been deleted now i'm sure there are a lot of errors because i'm not using any type checking extension or any golang extension right so there will be a lot of errors here so i need to start solving them one by one before i deploy it to the cloud so to find those issues and to fix them i'll head over to my terminal and i'll head over to the cmd folder and i'll say go build main.go and starts giving me errors right so it says on this file line number eight um yeah i can see the issue it has to be double right that's what makes it the or operator so you'll run the command again and now you'll get all these nice errors that we were expecting right and now you want to go start solving them one by one so starting from line 37 all the way to line 145 too many errors so when it says too many errors that means that even after you solve these it'll give you uh many more errors right so this is why i don't really you know use extensions because because golang takes care of everything it tells you which exact line which part what you're missing you don't like it's a no-brainer right you don't have to apply a lot of brains just solve these issues just like woodland wants you to and everything will run so that's why i'm so chilled out all the time man so if i can go back to your code on line 37 what could be the issue it's that i have not put comma here and comma here basic syntax issues right that's what it says it says basic index issues here also you need to put a comma and let's keep putting commas wherever you know i think um it will uh need commas so this needs comma here which is line 58 in my case you can check it out where you know it is for you for create user again i'll just put a comma here just to be sure and i'll put a comma in the input part which is this all right and in the update user function again let's go to the input area here i've put the commas so i don't see any issues here and for delete definitely you need to put a comma here as well as here as well as here so now if we run it a lot of the errors have gone away right and now you have some other errors there are some syntax errors also like four syntax errors and one this one also that you're not able to refer to this function so let's try and fix those as well at the same time so let's hover over back to our code let me see the line first line says 88 line 88 blah blah blah blah blah yes m is small whereas m should be large what was i thinking am i stupid you know that i was not able to that i didn't make the m uh you know large because obviously the function is martial map with the capital m right so this just means that no matter how stupid you are golang takes care of everything right so you don't need to be the smartest guy on the planet so let's look at other stupid mistakes one zero eight comma missing it's a syntax error super simple right it's even telling you expecting comma right i mean how obvious can error statements be and then people you know tell me download this extension i don't have downloaded any extension man golang does everything for me and uh missing statement after label 125 125 missing statement after label blah blah blah blah blah yeah obviously the is equal to sign is off and then 147 147 put a comma here auto after 147 and then unexpected yep found it now let's run it now let's see some more errors yes so it found us some more errors and now you have to go to line number 66 76 and 140 but these are not syntax errors so here you'll have to think a little bit as to why there's an error there so head over back to your code on line 66. line 66 yeah so it says let's look at the error it says cannot use results dot disorder items and something something something to do with this function called unmarshall map that is because you're receiving items not item you're receiving multiple items right so you can't use that marshall map function here you'll just re use unmarshall list of maps super simple man super simple 76 line 76 all right it says blah blah blah blah blah request our body see it says request dot body undefined and it also says does not have body with capital b right i mean you don't you can be the stupidest person on the planet and fix this issue because you just had to make this b capital right so that's how intuitive go language and then you go to line number 140 line number 140 i mean i can guarantee you that you can't do any like something like this with any other language right it says there's a problem with this function obviously because there's a spelling mistake here parameters so everything is fixed now and now let's see so it gives me another error that says unmarked list of map is wrong yeah because i made a mistake again it should have been unmarshalled list of maps not map awesome so now now that your user.go file is sorted as in it first shows you the syntax errors you've solved them then you solve the logical errors and now it's giving you some issues with the handlers file right handler.com it's giving you all these syntax errors we'll solve them then we'll give you some logical errors we'll solve them as well and then we're good to go all right so we're on the right path and now let's go back to our code so open up your code and start from line 19 line 19. put a comma here line 42 42 per comma here it's because saying it's exactly expecting a comma from you right and line 54 put a comma line 59 blah blah blah blah blah blah comma line 66 and 72 96 for a comma 72 for a comma all right now you start getting the real errors right the real errors so um line 22 we just solved this issue on the other file line 22 because the spelling of parameters is wrong and now you want to worry about line nine line nine so one thing to notice is that it's line 9 but of another file api response would go so open up the api smaller go file and here i can see there's an issue all right i have fixed the issue it was basically to do with uh those brackets and now it's starting to show me issues with main.go file which is what i want i want to fix the main.go file issues but on line 44 line 44 let me see what's happening okay yeah i can see it i can see the issue it's basically all the cases have to be together and by mistake i'd written this outside the bracket also the switch bracket and i've included inside so that error should also go away and now when i do this it's created the go build may not go file for me so let me see if it has yeah i can see the main file i just have to move it here to my build folder and i've created the build file without any issues no errors right so now let's start uh the deployment process before you do anything else you need to first create a zip file so you'll just come here you'll say zip minus jrm build slash main.zip from build slash main so build is your folder main is the build that you've created for in your folder and build slash main.zip will be the zip file using the zip function maybe in your linux you don't have zip you'll have to install it using sudoku apt-get zip so now if we check here we can see the main.js file in my build folder and now we're ready to kind of start uploading it on lambda or aws lambda but as remember as you remember i told you that i have windows installed on that i'm running the wsl on that i'm running this ubuntu and on top of that i've built this folder right so i need to be able to access this main.zip file from my uh windows from my windows to be able to install like upload it on my hero player school and lambda aws lambda dashboard so for that i'll do something so to in order to help me to do that i have to run this command explorer.exe dot and now hopefully it should open yeah it has it has opened up the explorer at this location for me and i'll copy this i'll put this on my desktop awesome and now i can start to deploy this on my aws console so you want to start deploying but there's one thing i wanted to change is this table name so i'll keep this table name same as my other name of my program go serverless yt okay just for consistency's sake because we will have to create this table in dynamodb and let me just search uh if i was using the other table name sorry i'll just ctrl z and i'll just see if i was using this table name anywhere else in any other file oh it's this only place there's only one place i was using it so here's the table name has to be changed you will say go serverless righty okay and now is when we start deploying so log into your console and head over to lambda you have to just create function go serverless right so we're using golang one point x i think we'll have to change the uh execution rules create new role from aws policy templates this option is what you have to select and the role name go serverless righty executor from the templates you have to choose simple microservice permissions create function successfully created right now you want to change the handler so as you know our main uh the file that we'll be uploading is called the main file that's what our build is called right so we'll have to change the handler to main upload the zip file and upload it go back to aws and go to dynamodb and you will click on create table table name so table name is what you selected here go server syt simple right because we have kept everything with the same name so and primary key so it says enter the partition key name i think this is the primary key yeah it's the primary key so the primary key in our case is email which is string obviously and everything else is same and we can just create the database active it's now active so now you can proceed to the next stage which is configuring your api gateway so head over to your api gateway create api you want to build a rest api protocol is test select new api here and now you want to put the api name which is go serverless yd and you then create the api from the actions select create method select any and here you'll select integration type lambda function and check this use lambda proxy integration and give the name of the lambda function here which is go serverless yt and you have to also have to ensure this is checked default timeout now we need to deploy our api so from actions deploy api select new stage stage name is staging and deploy so this is your url that you get here which you will be using right now to test so let's test it out i'm expecting some errors to be there but not a problem let's clear our screen and um first we'll have to build this command so just give me a second so here are my four commands and obviously uh this is post which is creating a user this is get all users get a particular user by email id and this last command is for update now we can use postman or you can you just use curl which is the same thing right and you set your header and you tell it what's the request which is post and the data that you need to send which is email which is my email address my name my last name and this is the the unique link that i just got this link is the unique link that i just got from my invoke url okay so i'll post these comma i i'll post this command somewhere how do i post it now okay so i'll what i'll do is i'll upload this project on github and then in the description i think i'll just post these commands so that you know you can just copy and paste them directly uh i think that'll be the best option or you can just use postman i mean you have to use these commands if you don't want to all right and similarly for uh the update you say it's request put you give the new data is going to find email based on that because emails are primary key as you already know and this is my api link these are the four commands i need one more command which is the delete command so i'll change that to this so you'll get all these in the um an api gateway documentation on how to call these apis you can get that also and so i'm just copying those and i'm just changing uh those commands all right so what we'll do now is we'll try and test it i'm pretty sure there'll be some error it'll fail but let's do it anyway oh so it worked it worked all right so it created this user which is amazing let's run the second command sorry this command and now it's not copying and pasting it now we're running the get all users command so we'll get all the users so only one user is there so it's getting that and then we'll get the particular user the particular user has this email id it will get that user also for me because there's only one user right now yeah so that's also working and now we will work on our put function so it's taking my email address and changing my first name to la la la and last time to blah blah blah blah blah right so it's done that so even update is working and now we have to work on the delete function so if the delete function works it won't return anything so we'll check if that user is still there so we're getting all the users so that means delete work because it's an empty array right the same user is not there anymore perfect so that means everything is working i hope you enjoyed uh this tutorial uh it's a it's a long video i know there's a lot to follow there's a lot to learn there and i hope you really enjoyed it i hope you learned a lot in this uh project and um very soon i'll have i'll have one more project coming up with serverless stack but it's a little more advanced we'll have multiple lambda functions we'll have cloud formation we'll have you know those cloud formation scripts so and everything will be through uh you know yaml files and then aws cli and we'll also use aws sam for the entire setup so that's going to be really complicated um so make sure you've done the aws lambda uh you know that video and you have done this serverless video and then you read up a little bit more about how serverless works and all the aw technologies and that will really help you in the next upcoming video that'll be slightly longer actually much longer and they'll have like way more complicated project right so the point of that is where this is like a monolith serverless project right that will be serverless microservices project there will be api gateway cloud formation uh there will be a lot more technologies i will use aws sam for all the writing all the configuration files anyhow so i hope you're enjoying it and do subscribe to this channel if you haven't already and there are hundreds of videos on golang on my channel check them out and i also keep sharing some nice advice on uh you know your development career so you keep watching that as well all right so see you uh and connect with me on linkedin there's the linkedin uh link in my description box below thank you in this video we're doing something very interesting we're building an intelligent chatbot so till now we've built many slack bots but most of them have had a hard coded command and response but in this case we're building an nlp aware completely intelligent slack bot so we'll be using four different technologies one is obviously golang because we'll be writing the code in golang then we have slack to interact with the bot then we have vit dot ai to understand nlp responses and wolfram to actually run the computational models and can get the responses from the internet okay so vid is a technology that facebook has developed it's very similar to dialogflow by google or lex by amazon and you can basically train it to understand different um sentences so for example if i want to find out who the president of india is uh so you can have uh different type of queries right you can ask him uh you can ask the what who is the president of india or who is the president of india now or who's currently who's the current president of india so all of these things right all of these statements they uh they basically mean the same thing that who's the president of india right now right but then uh slack doesn't understand it golang doesn't understand it so vet is the intelligent nlp part where vic can be trained with all these hundreds of different statements to understand that you're basically trying to say the same thing so it so it basically uh creates like a confidence score to uh tell you that okay i've understood the query now and uh you know i understand your question so what is that nlp intelligence engine right and then once you have once it has understood the query you can send it to wolfram world fam is the competition and so wolfram has the answer of who the actual president of india is it doesn't have that answer wolfram has that answer so so vit basically can be trained with hundreds of different sentences to actually understand uh what your query means and then it will send the query uh to wolfram and then we'll get the answer and then uh you know we'll get the answer to slack so let me take you through the entire diagram of how we're going to do it so the user will enter a message it goes to slack and slack then sends the message to us go lank server golang server then sends it to vit whit then sends it again to golang server and from there we can again send to vol from because there's no connection between width and volt ram and slack and width right so our golang server is going to be the connection between all of these things from wolf wolf ram we want to send the response to slack so it has to go through our golang servers right everything i'm sure makes sense now and there are going to be some packages that we'll have to use to interact with it to interact with cool uh wolfram to interact with slack so slacker is my favorite package if you've done my other previous slack bot tutorials i'm sure you know that there are many on my channel so you can go ahead and do those as well so slacker is the package that i often use so you can look at this somali slash lacquer right on it go on github so i've kept these tabs open because all of these uh are important to us so that's why i've kept all of these tabs open right i'll take you through all of these one by one so slacker is the um wrapper on top of the slack go package uh which is a wrapper on top of the slack bear uh api right right so this is like a third level abstraction of uh how we can build a slack bot and this makes our job very very easy so that's why i always use slacker so now that i've shown you this i can cancel it out i can you know close that tab then we'll be using uh with our commands that we get from slacker the user that he enters the command it we process it and are using our slacker and then uh we send it to witco right uh using vidgo vs into vid and that's how of it will process it so with go you can think of it as a wrapper uh around wits apis written in golang so you can use this as functions you all you have to just call these functions that are written in with go all right and now uh with gives us some response that we need to we need to send to wolfram right but the response that vid gives us has uh it's a really big uh json and to process that json it's uh it's quite challenging in the sense that uh if if you know how to work with json with golang you know that it's not very straightforward you have to use struct sometimes you have to use unmarshalling and all that so uh i found this package called gjson so first let me close fit go so i found this packet called g json it helps you query json very very easily so for example and now this guy is a genius obviously so i have to give him that so ted wall or actually there are so many more contributors in him so these guys are geniuses because they have built a package that helps you take a json like this and then just access them like you would in something like javascript right which is so simple so you if you wanted to get name uh so inside this entire json object is this uh key value pair called name which is an object itself so you can if you wanted name and last you could just say name dot last right and you could get access to anderson and if you have worked with golang you know how difficult it is to actually restructure a json object like this and then get an actual access to something like this right so uh so this library makes it very easy and i'm going to use this in this video and also in the future videos i'm trying to use this a lot more uh so that that will save us a lot of time right building all these structs and then unmargining and marshalling it and then trying to access this value and it's a lot of work so we'll use this ge json right so now that i've shown this to you i'll just close it off and uh to work with wolfram now wolfram is a big uh technology right it has a lot of apis it's quite complicated so there is somebody who has written a go wolfram uh package for us now this looks simple but as you can see there's so many structs right all these different stocks are there that help you to work with that help you to basically translate or unmarshal the data coming from the apis and then it's a big file it's just one file but it's a big file right so somebody has done it for us they're calling the wolfram uh api and then getting all the data for us all right so all we have to do is just call the functions inside the go over from package like so right so you can create a client you can get query results simple and straightforward so we'll be using google form like i said and we'll just close that off right now and the other thing that we need to use uh you know uh so you know that the way i manage uh environment so i don't uh so i since i make very beginner friendly videos i don't try and confuse you with uh you know trying to set your environment so i just use os dot set environment and os dot get environment that's i do something very very simple and straight forward but this is the right way of uh setting that environment so i'm uh if you might also know that i'm also a ruby developer i've been a ruby developer for many many years and ever since golang you know i started using golang i stopped using ruby uh many years back so uh so this is a go uh you know implementation of very famous and rupees.nbc very popular ruby gem right dot and here you call them libraries but in ruby you call them gems so this is very very popular and this lets you manage uh and your environment variables very easily right so all we'll have to do is we'll have to create a dot and file and we'll put all of our uh you know keys there and then we'll be able to just uh load it simply with go dot invert load and then we can easily use them with os.get and environment variables right so this also means that i won't be pushing my environment file into github so you need to create your own environment file with your your own apis api keys so pay attention when i show you how to get your api keys uh because that can be confusing to some people right so this is the golang sorry the wolfram uh portal uh now one one uh thing that i have to tell you about wolfram uh website is it's very slow uh it can be a frustrating experience to work with it because the website somehow is stuck in the 19 uh sorry the early 2000s it's not it's not a new website it doesn't work like a modern website would and the api is also kind of shaky so obviously the the wolfram go package makes it easy for us but uh but i'm just telling you because if you can see this it's still lowering since yesterday actually so don't get frustrated just try to you know be patient and also it gives you only 2 000 requests per month so and it you can make only 20 apps uh at one go otherwise you'll have to upgrade so just make sure you stay within those limits if you don't want to uh pay a lot of money to upgrade all right and i have created these two projects here so if you want to create a new project you can just go ahead and say get an app id and before that obviously you have to sign in to you have to create an account in wolfram alpha you have to sign up and then you have to head over to developer.wolfram.alpha.com and uh as you noticed i clicked get an app id a long time back and sometimes you have to refresh it and sometimes very weirdly it would have logged me out but no not today it has not logged me out now so anyhow so i'll just click it again so now it's asking me for my application name so i'll say uh new nlp all right so i'll send you an lp what this is the youtube demo bot if you don't give a description it won't let you create a new app so i'll say create an app so it has given me this app id but but i won't be using this app id i'll be using my old app id the the one that i had created yesterday which is the nlp what uh sorry the wit ai one which has uh already has 13 total queries the reason for this is very simple uh with wolfram uh if you have not uh if you've not waited for 24 hours uh it won't let you use uh as in it gives you a lot of error sometimes and unpredictable type of error so it says uh you know invalid app id or some some editor like that so i looked it up on stack overflow and the answer that i found was that you have to wait 24 hours sometimes or at least 12 hours for the api to work correctly so uh if you create an api right now api right now chances are you won't be able to run this program properly and we'll say error app id invalid or something like that okay so that's the thing with wolfram alpha i know there are a lot of quirks with this so basically just remember to get your uh app id from here and that's all that's all you need to do at wolfram also website all right so just copy and paste it with yourself and then let's come to vid ai so here you'll have to log in using facebook because it's a technology built by facebook so we'll say continue with facebook it takes a while so i have all these bots built up and now we'll create another app called new app and let's call it then i already have a new llp so i'll just say with ai i'll just call it youtube demo all right so remember to keep it open and we'll say create and language is english and now it has a couple of things on on the left side right so you have your intense entities so we'll go to intense we'll create an intent and we'll call it uh let's see if there's a wolf ram intent already so there's no old friend intent so we'll just call it wolf ram and next right so we have this uh intent now we'll have to create entities so we'll create an entity and we'll find a built-in entity so we'll look for wolfram so the integration between wit ai and wolfram is so deep that they actually have an entity called wolfram search query so vdi would come to know that this is a wolfram search query and needs to send it to wolfram so it'll give us a relevant format so we'll say next and now we have our entity setup and this role is added by vitiai themselves and now whatever uh you send it to uh with ai right these will show up in your utterances so we won't actually write utterances and train our vti right now this is that's not the scope of this video you can find thousands of videos that train your vti or your dialog flow bot right we won't be training it we will be sending it very straightforward questions that will just identify as uh a wolfram uh query and send it forward so for example if i said what uh sorry who is the president of india right so with 92 confidence it is understood uh this question right so we don't have to train it right now that means so um but if you wanted to train it for this sim same query with multiple different uh statements you could do that right so anyways we won't be doing this like i said we won't be training it we're just sending it straight queries which are directly sent to wolfram so now that i've shown you the go dot end package i'll just delete that i'll just close that tab as well and i've shown you this video uh which doesn't work anymore so we'll close it so we won't be using any of the packages that have been used in this video we're completely rebuilding everything from scratch so we'll close this as well and we just need to keep our uh you know these videos tabs open just in case you need your uh app id so yeah i'm not showing you how to get your app id and video right so all you have to do i think um i don't remember correctly you go to settings and you will take your server access token this is the one that you want to take all right so just copy and paste that copy and keep it for now at least then let's go to our slack so slack i'll have to go to dot com api.slack.com apps and here uh if you have done my previous uh slack bot tutorials which there are plenty of you have built all these bots with me and today we are building another bot from scratch and we'll call it the youtube demo app all right and i'll select all tech as my space so it's called youtube demo and you have to switch on the socket mode so that it can catch up messages in real time so we'll say enable and we'll call it the socket token generate and you need to save this somewhere and keep it and but i'll come back for all of these api keys uh you know but you can keep them somewhere safe if you want and then we'll go to our event subscriptions we'll have to switch these on and we'll have to give it some events to subscribe to so we'll say app mention because we'll mention our bot and then we'll say message.im so these are the events that the bot will subscribe to so that it comes to know when something is happening so like let's let's say somebody mentions the bot and sends it a message it will come to know right so i'll just say message.groups as well and i will say messenger npm i am and i think that is about it i don't need to add any more uh events so always the trick with the slack is add more events than you think you'll need and add more oauth permissions so we'll come here and we'll add some oauth permissions so for now i'll just save these chinese changes exchange is saved let's go to oauth permissions and here we have to add some more scope so these scopes were added based on the events that we subscribe to but we have to add more scopes right so again with scopes the trick is to take more scopes from your from oauth of slack than you need so for example i need uh this one here called channels read and chat right because i wanted to be able to write to a channel right and i will say i am read and i am right instant message i am basically stands for instant message and i'll say mpm i am an npm read and write as well i might not need most of these permissions but i'm just going to keep them anyways like i said you know you uh they're so if you've seen one of my like my previous videos of slack you know that a lot of uh errors happen because you don't have enough permissions and slack the problem with slack is it won't even give you errors uh the right errors right so you'll keep struggling with the error for a long time and you won't know what happened because you won't get the right error so and most of them are to do with uh permissions in the sense your bot just won't work and you won't come no why it's not working so i think i have all the permissions that i needed and that is about it for me and i'm going to install it to my workspace and asks me if i can give it these permissions i said allow so now it's given me a bot user token so this is important and in our basic information the slack the socket token educated and that's that's important right so it's called the youtube demo just remember that so we'll have to uh refer it right we'll have to mention it in our slack channel so if we go to our slack channel and i say youtube demo so uh it's his youtube demo is not in this channel yet so do i want to add it i'll say yes add channel so add youtube demo to this channel only then we'll be able to interact with it right now what we'll do is we'll actually start creating that project so i'm not sure if you can yeah i think you can see my power shell so even if you're on windows or uh which is which is i am i'm in windows and i'm using powershell even if you're on ubuntu and using terminal or mac using terminal the commands will be exactly the same so what i'll do is i'll say mkdir and youtube demo nlp all right so i'll just go inside that and here i'll say go mod in it and github.com and it'll be what so uh the mod file is initiated like this so if you're from a javascript background this is very similar to npm in it so it creates a mod file which contains all the package that we'll be using in this project and this is the direct the absolute link that we'll use to access other files in our project so i'm not sure why the enter is not working on this maybe something to do with my internet yeah so it has created a mod file let me just check now what we have to do is we have to start getting our packages that we need the external packages that we'll be using in our project so you can give these in commas or you don't if you even if you don't give them it's not a problem so you'll say github.com slash uh if you're from a javascript background this is exactly the same as npm install and this is the name of the package and this is the github link for it so like you have uh the npm library the npm website nbmjs.com where all these packages decide uh golang doesn't have something like that so you have to get everything from github.com right and what we'll also do is we'll get go get github.com slash dot env and when you also get go get github.com slash uh the the slacker slack bot uh library that we need and we need the g json the one that allows us to query json with golang json sorry you have to write go get in front of it and then the last one we need is vidco the one created by alex so we have all the packages in place and all we have to do is open up our vs code and start writing the project right and here obviously the file that you'll create is main.go on top you'll write package main you'll write import and import all the packages that you need and here you'll have to write the main function so we'll say funk main and the funk main will have quite a bit of a code and at the same time we will have our dot and b file in the dot envy file you'll have four things one is slack bot token then you have your slack app token then you have your bit ai token and your wolfram app id right so volfam app id have shown you how to get it right from where to copy it i already have it copied in some place in my laptop so i'm just going to come and paste it here with ai token i've already shown you where to get it from copy and paste it here and then we have our slack bot and slack app token for the slack bot token you'll get that in your oauth and permissions you'll get your slack bot token and in your basic information you'll get your slack app token here in socket token that we created the one that starts with xapp is your slack app token the one that starts with xp is your slack bot token all right so now that that's clear i'm going to copy and paste my uh sorry i forgot to copy my tokens so i'll just copy this i'll say copy and this is my slack app token and slack what token i have to go back to oauth and permissions and copy it so our environment file is ready now we will have to import some packages that i know we'll use when we will use context and coding slash json we'll use fmp to print out stuff and json to you know work with json log and os for our environment variables and as of now i need slash shoho slash go dot environment right we we need uh other packages as well with for working with slack and wolfram and width but i'll introduce them one by one so in our funk main the first thing that we write is go dot environment and here we'll use the load function to load the environment file okay then we'll create a bot so we'll say bot is equal to so here we have to create a new client for our slack bot and that can only be done if you have the slacker package so we'll say github.com okay so let's create our bot the bot basically will have slacker dot new client os dot get environment and slack bot token comma os dot get environment slack app token so these are the two things required for our bot so let me see if the brackets have been properly closed so we have we have an extra packet here by mistake to remove that and there's one more extra bracket here by mistake so we have to remove that as well so all the squiggly lines have gone away and uh there's a squig line here with bot it's saying it's declared but not used but we'll use it soon so you do not worry about that and then there are squiggly lines with all these packages you will be using all these packages soon so you don't have to worry about them as well okay now uh since we are in the process of creating these different variables i think it's uh a good time to create our with ai client and our wolfram client as well or maybe i'll do that after a while anyways so one thing that i have to do is i have to create a function called print command events if you followed my other slack tutorials as well slack slack bot tutorials then you know that this function is simply to print out the events that the bot uh subscribes to so whenever we put a give a command to a bot uh it acts as an event and it uh publishes to the command line we want it to be open to the command line so that we come to know what's happening so we'll create this function now so this function will be created above funk main and as you know we'll call it print command events so in one of the previous videos i've already explained uh the inner dynamics of this function basically your passing command event here and we'll save for event we'll just range over this analytics channel and we'll print the timestamp of the command the command itself the parameters that it received and the event name so let's say fmt dot println we'll say command events and fmd dot println again event dot timestamp fmt dot print ln again say event dot command fmg dot brilliant render and event dot parameters like i said and the event itself and just an empty line so our print command events function is ready now i had a couple of packages here and when i pressed save since i'm using this uh golang plugin it removes all the packages that i'm not using the code right so by mistake don't press ctrl s because it will remove all the packages that we had uh you know written here but it's not a problem so what this uh golang plugin does also does is that when i use a package here it also adds it here on top so it's a two-way street anyhow so we have written our command for printing the uh the events the command events and now we'll start working on our uh pod.com function which basically handles the command that we'll send to the bot but before that we just have to write in some code that will help us stop the program and we wanted to so we'll say context dot with cancel again this is standard code that we've written in all of our previous uh slack bots right slackbot codes so in case you're new to this channel there are hundreds of i won't say hundreds with here at least tens of uh slackbot tutorials do check take a look to check them out is equal to bot dot listen ctx and if there is an error that means error not equal to nil we will say log dot fatal and we log out the error all right so like i said this is standard code and i'm using the log package here and now it's installed the package for me it's imported that right earlier it was giving this quick line here so we have uh the outlines of our function ready and now comes the main part which you need to pay a lot more focus to attention to sorry it's the bot.command function which basically helps us to uh you know understand the commands that we give to the slackbot and then work with that so we'll say bot dot command and here we'll uh you know put the command that we'll send to the plot and here we'll say slacker dot command definition and inside command definition is where all the magic will happen all right so this function obviously the command function is part of the slacker library and this is the syntax the requirements of the function itself and it has uh a description so we'll say let's say send any question to wolfgram and has an example again like i said you know this is coming all coming from the slacker library it's not something that we are building up uh all these are requirements of the slacker library so this is an example right example question these are uh both are static variables these are just the description and the example of how the spot will be used right these are not dynamic so we'll say handler handler is our function that helps us to work with the bot or with the different uh you know commands and when i pressed enter it it filled in all these things for me automatically so in case you're not using a golang plugin and it's not filled in these for you just make sure you get this right otherwise this code will also be on github and you can easily pick it up from there so we'll say query which is a variable and we'll say request so handler functions if you've seen my rest api videos of golang you know that you have requested response objects right so request is what the user is sending to this function to our golang program and in the request you will have parameters if you've ever worked with rest apis you know what parameters are so the parameter that you're looking for let's say it's called a message right and here that means we have to uh give a query something like that so we'll say query for bot right put a dash here and to pass a param in a function uh to to slack when you pass a param you have to pass it like this so we'll say message and so what you're telling to go language is that in the request there'll be param called message so when we send a command to our slack bot it'll be like query for bot and then we'll put a dash and we'll put the actual uh statement and the statement itself will be captured inside query and then this query is going to be sent to uh you know wherever like uh wit ai and wolfram now there is a there seems to be an issue here i think we have to put a comma that's what the vs code is telling me so i've put a comma here and the squiggly lines have gone away so everything looks good and query there's a squiggly line here because it says it's declared but not used right now what we'll do is we'll come here we'll say client dot parse now client is going to be our with ai client which we have not we've not created till now so i think before i create my client what i'll do is i'll show you what the query looks like in the uh command line so i'll say fmd dot print line and i'll say query so when we send this uh query to the bot it's just going to print it out and then let's also keep a response here and the response will be very simple just be received all right now reply gives us a squiggly line because r has to be capital and now everything works except for this i don't know i could not import this package i think we'll have to just run go more tidy and reinstall it back again so i'll just go to my terminal and i'll say go mod diary even i have if i had installed the package i don't know why it wasn't recognized here so anyhow uh this is what uh the code looks like as of now and there seem to be no errors so what we'll do now is we'll start this program so we'll say go run main.go and let's see what happens okay now we'll head over to our slack and to our youtube demo app we'll say query for bot and we'll say what is the capital of india so all we need to know is that yes it was able to get the message so message now is what is the gavel of india so it's able to read it it's also able to print it out right so everything works as expected and this means we can now start writing the code so now we'll create our with ai client to do that you need to create a variable called client out here so let's say client and the walrus operator and then we'll save it ai we don't have ati in our project so let's get fit ai in our project so we'll save it ai and the package will be github.com slash weight ai slash wait go slash v2 now we had installed this package but there's a possibility that uh golang wasn't able to get it it's okay we'll again run go mod id no problem so coming back here we'll save it ai dot new client we'll say os dot get environment and with ai token now again the reason that why golang is not able to get this for us is because because there's some issue with my go path obviously and since this is my windows laptop i won't try to fix it i use my linux laptop most of the times so just bear with me when i run go mod in it uh don't worry it'll install it back again for us so here we have our client with ai and it uses the vti token in our environment file all right so so far so good now it's giving us a sweet line here because we have not used our client package and that's what we'll be using here so we'll say client.parse and inside parts we'll write with ai ampersand with ai sorry in small what's wrong with my caps wait a i dot message request and side message request you will have to send a query and the query will be what you get from here from uh your slack bot so let me show you the diagram again all right you the user sends a message it goes to slack slack gives it to golang server and now we have to send it to it right so slack has given it to golang which is query and query has to be passed to vdi so i hope everything makes sense now and here we're going to print this out so we'll come here and we'll take these values in a variable called message comma blank and we'll print out the message here so now we'll run that program again and i'll show you why i've done this uh i'm not sure why it's telling me to get this package when i need the v2 and if i say command s and i run go more tidy i'll just stop this program for now i'll say go mod tidy and it has got the v2 for us right so everything works now no errors here so we'll run the program again oh yes sorry sorry sorry sorry i'll run the program again i'll say go go run main.go and here we'll say at youtube demo query for pot what is the capital of india and it's able to get the message and now this is the reply that's coming from vta this needs to be structured i'm sure you agree with me that this needs to be structured because this is not something that world ram will be able to understand so we'll stop this program here and i'll just open up the vs code editor again so the message that's now in msg we have to do something about it right so we'll say we'll create a variable called data we'll put a dash here and the walrus operator and we'll say json dot marshall indent basically want to convert that whatever response that you saw you want to convert that into json so this adds the right spaces and everything so about four spaces is the right one two three four all right and uh this will add those uh if you've seen json objects you'll you'll see that all of the key value pairs they're covered in these type of inverted commas right so that's what the double inverted comma sorry so that's what the indent function does so json is giving a squiggly line here so if i put ctrl s that should give me the encoding.json package yes so i get that so there's only one error left which is data which is basically saying that i'm not using data and i'll create another variable called rough and i'll say convert whatever data i get into string format and we're going to print out basically this rough variable now let's see what happens we'll run the program again and here we'll say at youtube demo uh query for bot what is the capital of india it does says it'll say received and here we can see that we get a nice json object that now we can work with and uh the thing that you need access to is basically inside entities inside this wolf ram search query and inside that array inside that object inside the array and inside value that's what you need the reference to right and this value this is the thing that we need to send to wolfram now there is also a confidence score which is of 92 percent so uh 92 divided by 100 is 0.92 so so it gives us a range between zero and one so anything above 80 percent or even 70 is good and we could have you know taken our program further and we could have uh checked the confidence score and then uh given the query to wolfram but it's not a problem since we have not trained our bot to understand these queries as of now we won't uh and and our vita ai is directly going to forward these queries to voltram we don't have to worry about the confidence score right now okay so you'll stop this program now and it does give a little error a problem time to you know stop it and here you'll come back here again and uh now like you know you need access to this thing right inside entities inside this inside the area inside the object inside value now to get access to this ngo line is very difficult it's not like javascript you just you know start accessing this uh working with this object directly because golang does not have native support for json because json is javascript object notation so only javascript has native access to it so what we'll do is we'll create a variable called value because we need that value right inside entities and we'll use our package the json package and with the json package you can just run these get queries to get whatever you want so we're going to run the get get query on this variable called ref and we want to say entities so i want access to my entities and i want access to this width dollar wolf ram search query and uh you know colon wolfram search query right so let me write that here with dollar wolf ram search query colon wolf ram search query okay so just check if the spelling of wolfram is okay looks good and now we want to access the first value of this array right this is an array so we have access to this now we want access to this first value of the array so we do that in an array do that by dot zero right because that's the first value so with this package with the help of this package you can easily access the values inside an array so you'll see dot zero and dot value so let me show it to you again so dot zero which is this object and inside that is dot value and you'll have access to what is the capital of india it's just as simple as that now what we'll do is we'll actually print out this value so that you'll see exactly what i'm talking about and now we'll go here again we'll start the program again okay so it's telling me to get this package so let me go back here okay again i'll run go mod id and we'll run the program again okay and here we should say again the same query query for pot what is the capital of india here you can see we got the value the exact string that we want to send to our wolfram we have it here we were able to access it using our uh gjson package makes sense so uh with the help of uh this bot right we'll be able to send it send these kind of questions like who's the president of u.s who's the president of india who's the president of the u.s what is the capital of india who's the governor of china it'll give us the exact right answers uh because wolfram has the ability to process that kind of information give the right answers so let's see how it does that now create another variable called answer and this basically converts the value that i just received here into string okay because string is what we have to send to our voltron client now that means we'll have to create our world front grant right so we'll come here we'll say wolf ram client is equal to ampersand wolfram dot client inside that here in this case there will be these quickly brackets and we'll say app id os dot get environment and we'll say wolf ram app id all right so it doesn't our golang program doesn't have access to this so let's fix that so it's added that already actually good and then it's giving me error here okay i think i'll have to create a wolfram uh client actually a variable call voltron client so this i have to make sure the cs capital c has to be capital here and here i'll have to create a constant wolf ram plant and wolf ram dot client all right and the wolfram client comes from here everything looks good right now there seems to be an error here i don't know why missing constant value syntax sorry it has to be a variable actually or a constant so it's a variable and here so it has an error here it has an error here in this place and it has an error here because we are declaring it but not using it so now i'll come here to answer actually before that let me just stop this program and go more tight again so that we get the word from package and now the errors mostly have gone away except for these two errors right the word from clients so this the volume 10 we have to use right now so i have the answer here in a which is basically string in the value in string format and i'll say world ram client dot get spoken answer query now there's uh there's a confusion here that many people have is that uh the person who's created this library it should have said get spoken on security but it says get spoken in t there's a small t here so just make sure you write that t otherwise you will face a lot of problems so here we'll pass the answer comma the answer that we get here and wolfram dot metric comma 1000 all right and we'll assign this to two different things one is the response and one is an error and if there's an error which means if error not equal to nil we will print out there is an error and the response we will send our response object rds right and to me everything looks okay and there seems to be no error as of now but only when we run the program we'll come to know so yeah everything looks good and what we'll now do is uh let me check if there's any uh more packages to be installed i don't think so okay so let's run this code go mod sorry go run main.go and to our youtube bot we'll say query for bot what is the capital of india so it can reply to us the capital of india is new delhi india and youtube bought query for bot what is the capital of china it takes a while because it goes to wait and then goes to voltram see colossians beijing china so as you can see our bot can understand anything you know it's really really powerful so let's say query for bot who is president of india at youtube query for pot who is the president of brazil so as you can see our bot can do anything it can basically uh find the answers for all of these very difficult questions uh that and uh difficult in the sense not for human beings or sometimes even for human beings because i didn't know the president of brazil is right so yeah you can get all of these answers from using your wolfram api so i hope uh you learned a lot in this video today and you built something really exciting and this is a very very powerful bot so if you're by the way if you're somebody who's looking for a job in golang uh i don't think there's a project that's better than this to show off your skills right because you're using golang you're using slack you're using uh and these all these awesome packages right environment packages and the json package and you're using um vid you're using wolfram and then the sky is the limit with it right you can i didn't show you how to train your vid bot but you can you know you can basically watch any other video on vid uh there are many videos on that focus on just how to use fit and you can actually you know scale this spot up to a whole new level right so i hope you learned a lot in this video and uh we built a board that can basically do anything right it's an nlp what and it's connected to wolfram so it can understand anything it can do anything so i won't say you can sign anything because we are not trained of it with api but if you trained it really well it would be able to do anything\n"