Postgress With Go Using GORM - complete series in single video

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] um what is up guys how you guys doing in this video we're doing something very interesting if you're going to be using postgres with golang now I've received a lot of requests and a lot of comments on my YouTube channel asking me how to use postgres with uh golang and I wanted to show you uh show this to you in the the best way possible or the easiest way possible at least so uh the easiest way that I think to use postgres with colang is using gorm right so you want to interact with the server golang server with postgres and the easiest way to do that would be using Gordon and also there's a video on my channel uh the MySQL with golang video right and that has uh become really popular it's gotten around eighteen thousand or Twenty Thousand views or something like that so what I'll be doing is I'll be using a very similar code that I've used there in the sense that we'll be using gorm just like we've done in the MySQL video and we'll be using exact similar kind of apis as and we'll be working with the books API right so we'll have a structure called struct call books and we'll be working with books apis at the same time we'll also um use Fiber so that's something new that I'll be adding to the mix um like in that I think the MySQL video we use something else we use probably mux or something like that here I'll use Fiber so in essence essentially what you're learning here is you're learning how to use golang with postgres but also uh with the help of fiber so how do you use all these three things together now I'm not sure if I'll be able to complete this in one video because I'm slightly pressed for time I mean I have um a few tasks to get done after this so I might have to break it down into three small videos uh I'll have to take breaks and probably but tomorrow I'll have to upload the second part and third part and so on so this may be to divide into small parts um but those parts will be like three or four not not more than three or four parts because this is not a big project it's a small project just want to show you uh by building a simple rest API I just want to show you how to use postgres with go like nothing complicated out here not a big project Max three or two four three to four small videos I would have done it in one video that's what I wanted to do but I'm just really pressed on time so I'll have to um you know shoot tomorrow instead anyhow um now let's start with the project so firstly we have to create a directory called um go fiber or stress and we'll see the input then we'll say um go mod in it and whatever name you want to give to this project I'll obviously give github.com and slash my name and the name of the project which is full fiber Chris now go mod init works like npm in it where it creates a go dot mod file for you which is the equivalent of package.json file in node.js right so a lot of people who are learning golang come from a JavaScript background so I try to inform them this command is like NP a minute basically and with golang you give these absolute paths right so whenever so we don't have like an npm kind of a scene here in golang so whatever pack even the packages that you create you have to host them on GitHub and this is how when you import packages the third party packages you don't have like an npm you know import packages that look like this these kind of links okay anyhow so what this means is that this would have created a go.mod file for us which will have the list of all the dependencies that we'll be using in this project called the external dependencies and I'll open up this folder in my vs code you could be using anything else but vs code is the one that I prefer uh usually and um a couple of extensions I'm using so if you go to your vs code and you type volang the first two or three extensions that come up are I I use them usually the first two at least so let me install this in WSL yeah that'll keep happening on the side now it's it's asking me to install this in WSL because I am using Windows and I'm using something called as WSL on top of Windows uh actually it's it's a part of Windows the Brazil is part of windows but wsn allows you to um use Ubuntu inside of Windows and multiple Ubuntu instances so if it works for me because I have to work with different versions of open tools for different type of projects right so I just installed the first two golang extensions that come up uh it's just going to help you to fixed code in the sense it'll give you those squiggly lines Whenever there are issues and that kind of stuff in my earlier videos one go on YouTube I have not used any extensions and that's because and I stick by that I say that as much as possible try avoiding uh avoid the use of extensions because uh when you are called for coding interviews you're not allowed to use your preferred or favorite um you know what you call it IDE your preferred IDE you know they'll probably have just a window with a screen shared with the interviewer and they'll be their own built-in IDE in the in the in their app that they'll use and that's where a lot of people that I mentored they get into a lot of trouble there because because they're so used to working with all these extensions so I'm just using them here because a lot of people have told me the use extensions that will be just better for the viewers I'm just using it for the viewer otherwise if you're a programmer if you want to get serious about programming I would suggest don't use a so uh out here the first folder that I'll create will be models then I'll create a storage folder and then you'll just create your EnV file and you'll create your main.co file so mean dot go file as you know is the most important file in a colang project and what we can do is we can start working with the main.co file so the main.go file we're going to say here is you can say package you will import a few packages we'll talk about that in a minute and um so the most important thing that you'll do here is basically your funk name so you'll come here let's say and we need the dot EnV file to be imported so we'll say go dot PNG which is our in the package we'll import it shortly and we'll import the dot inv file okay and when you run a function like this you highly want to capture the error and handle the error out here so error is not equal to the mail you want to say log field caters okay now what you want to do is you want to say app is equal to fiber.net that means like I told you we'll be using the fiber package to create these routes and a lot of people coming from a JavaScript background they really like using fiber and the reason is that it works in a very similar syntax to express and the inspiration for fiber is expressed only fiber is I think they say it's 10x faster than Express or something like that it looks very similar while using it but it's like way faster than Express right the whole expression not just platform it's it's this is coolang is obviously way faster and but but what you do is you create this variable called app and you say r dot setup routes which is a function that we create right now and send app to it and then you can say app.listen very similar to node.js right on 8080. Okay so the celebrities is not a simple function and what R here is R is basically a repository so what we'll do is we'll come up here we'll Define a repository okay and the repository basically will be your database called Dot so first let me import these packages and things will start making a lot more sense to you so here it will say firstly obviously I need my github.com fiber slash fiber slash we do I need my fiber package I need gorm.io and I need go dot environment because we've used our environment out here we'll have to import it so I'll say um github.com [Applause] all right now all these links they exist on GitHub so uh you don't have to type these right you can just go to GitHub and just copy and paste these links I'm typing it because in case if you want to type it you can type along with me okay so this this is how you um like we've imported these packages and now what I want to tell you is that um in Funk main you'll have to Define art first okay so what you'll say is r Repository and the db4 repulsory will be TV so you'll have to Define DB as well right so DB is a variable that we Define shortly which will be basically um you know our database but let me first tell you what's going on out here right so you might be confused what's R what's repository what's happening out here so repository is a stack that we have created on our own now struct uh Stacks are your own data types that you can create so you have uh strings and integers and or floats and all of those things with golang but while working with golang you also want to be able to create your own data types and colang gives you that ability golang says that you can use something called a struct to create your own data types so I've created a repository which is my own data type and it basically has DB now DB is a pointer to gorm.db which is gone right and has uh it gives me the ability to to interact with my database um now when I create repository here inside my function when I actually create the repository which I am capturing in this variable called r so that means R becomes a repository right so R becomes a struct of type repository and it basically has DP obviously because whenever we instantiate R which is our type repository it needs to have DB right that's what the struct does and the value we'll get from DB that that's what we need to work on we need to work in this variable quality which has a small D and small B whereas DB this variable it needs to have has a large capital D and capital B and in our function setup routes right we send a app but as you can see the way we are calling this function is very different we're saying r dot setup routes now r dot means that um it's not simply a function it's actually a method a struct method stuck method is uh like a function but for those specific studs so that you're able to access those tracks inside that method okay um so what I'll do is I'll create this um method called setup routes because it's going to be quite straightforward so let's say R star Repository so now you'll be able to easily access repository inside this function so you'll say setup routes and this function accepts fiber.ap now this part right if this part was not there in this bracket are star repositories and that would mean that it's just a regular function but just because this part is there it now becomes a method a struct method and here I'll say I'll Define a variable called API I'll say app why app because app is something this function is getting from here right we're passing this app variable at 50 which is an instance of fiber.new from function we're passing it here we have access to it here so we'll say app.group that means all these apis that we're going to talk about are belonging to the group slash API so all the other ways will start from slash API so let's say I have API Dot post you have uh create now I have taken the example of books because I want my viewers who have already worked on my MySQL and golang our video with me I want him to feel at home here as well so that you know you can relate we can compare you can understand the differences that happen here with postgres which are not a lot by the way not a lot of differences happen when we use postgres but postgres is very very common and I think popular so that's why everybody wants to know how to work with postgres using um golang okay so you'll have a post uh method with this API create books but all of these will belong to the API Group so you'll have API slash create books right and if you use post method you will be able to call this method called create book now as you can see I I didn't say function so you're not calling a function called create book you're actually calling a method called create book because they'd all be repository methods or methods of type struct which is Repository and here you'll also say API dot get slash get underscore books comma slash ID comma r dot get book by ID here you will say API Dot get slash box comma r dot get books okay so um now what I'll say is um there are a couple of things I can do but let me just work on this TV for now so I'll say DB the small DB right well equal to storage now we have not talked about what storage is don't worry we'll have a function called new connection which will basically take in your config basically things from your config file which is EnV and here um foreign so this header here itself here handling so it's a log box fatal because [Applause] [Music] it's okay so the storage right store it is something that we'll worry about in a while but before that I want you guys to think about the book right on which everything all the operations will be performed so the final book here we'll say a book construct and the bookstract has an author as a title publisher and author is string title again string publisher again now uh one thing one and one thing to note here is a confusion that a lot of people coming from JavaScript have with golang is that golang basically does not understand Json on its own uh with JavaScript you use Json so much because Json is Javascript object notation that you start thinking that all languages understand Json which that's not the case only JavaScript understand Json so for golang to be able to understand or work with Json you'll have to um tell colang as to what this variable is going to look like in Json so the way to do that is you'll say Json and this is going to look like this author so that means is that author has a small a whereas the author that golang knows understands and is expecting as a capital A so our job is to do something called as decoding when we send a post request using our Postman to golang we'll be sending information in Json format but with the help of decoding we'll be able to get access to the struct which golang understands and then we'll be able to work on that start right here again you'll say Json and Json this title looks like this title with a small t similarly for publisher this is what it looks like publisher okay now since we're using these third party packages and we we start getting these Squiggy lines telling us that these packages don't exist what you have to do is we have to go back to our terminal and basically say go mod tidy and in the background we'll start you know finding those packages and pouring those packages for us uh now there are obviously a lot more things that we have to do here and um I'm slightly impressed on time so what I'll do is I'll have to keep this video uh I'll have to leave this video here and in the next video we'll continue um from from where we left off and we have a few things more doing main.go and a couple of uh obviously we have to create these two files and we'll have to work on all these functions as well the create book read book and get Booker ID all these four functions now obviously you need postgres to be installed on your machine I'll leave a link to the digital ocean article for installing postgres in the description uh for this video so in case you don't have it installed we haven't reached the part where we'll start connecting our golang with posters but just as the note if you don't have process installed you need it and I'll send I'll put the link of the article in the description box okay now the second question somebody was asking me in comments yesterday so it's good that I was that I didn't upload this video in just one go and I uploaded I'm uploading it uh you know in in pots so somebody asked me uh you know that they use phpmyadmin to work with mySQL what interface am I using to work with postgres so I'm not using any interface I'm just using the psql uh command line CLI that postgres gives you that's what you can use to create your um uh your table or whatever okay uh now coming back to postgres to the project sorry so coming back to the project now we have created all these routes and these functions are not there so that's why we're getting these quickly lines out here so we'll start creating these functions quickly so we'll come up here for the create book function so we'll say func create book now it's important to know that it's not just a function create book is going to be a struct method so we will say uh R and Repository repository is the struct that you have defined here which basically is going to help you talk to the database and R is the initialized repository that we have created on here so all of these stuck methods will have access to R which is a repository and it takes in context which is basically fiber.ctx and this function is going to return errors so you will create a variable call book [Applause] which is of type book which is book is struck out here and we'll use context dot body parcel so what's happening out here what's context or body parts are doing now if you are using HTTP let's say you're not using fiber you're using HTTP you would have gotten access to the request right so you get access to W and R with HTTP package so where R is the request now fiber is a level of abstraction in the back background it's obviously working with your response and your request only and with the help of contacts which fiber dot context provides you you get access to the body and then you'll use body parser to convert whatever Json that you're getting into book format now like I said kolank doesn't understand Json on its own right so we Define how the Json is going to look like and we have also defined the struct that golang understands now we need a way to decode the Json information into the stack that Cola understands you can do that using the Json encoding package but you don't need to do it here because fiber already has uh the ability to do that for you so it gives you a level of abstraction and people do get confused here this is why I explained this a lot of you would already be knowing this and I don't have to explain it but for people who don't know this and will get confused out here so I thought I'll just pointed out that you know this is what fiber is doing so we use all these Frameworks like Fiverr and gen and we think that they're doing a lot of magic but they're not doing a lot of magic they're basically a level of abstraction over things that you would have to do manually on your own anyways so if error is not equal to nil you will have context.status [Applause] case repeat Dot status on processible entity dot Json here in the Json I'll boss fiber.map message request failed and we want to return the edge so again you're using fiber and you're using the map function to basically send a Json request right and this name of the error is wrong now it's giving us quick line here because obviously we don't have the history package so you can do that here you can say next slash http this is all right so that issue has now gone away okay so um what you'll do now is so now we'll obviously add it to the database [Music] um I'll come here okay and you'll say R which is your repository right R is your repository it has DB so I want to access that DB so I'll say r dot DB Dot create function and Ampersand book Dot N okay and here what we'll say is we'll capture this in our variable in an error variable we'll capture the error out here and we can handle here so we'll say if error is not good now context dot status HTTP dot starts batch request okay and the Json you're going to say could not create the book right because this is you trying to create a book using the database and if you are not able to do it you want to send an error saying that you were not able to could not create okay and this bracket ends here from here you'll return error and out here you'll say context dots status HTTP dot status okay so if everything goes well there are no errors right we want to send 200 error message so not edit message 200 status so here we will say fiber.map and message is going to be that book has been I'll take it on the next line actually it'll just look much neater so let's say book has been added okay that's perfect now what you'll do here is you'll return return ly because we're supposed to be returning an error make sense it's supposed to be doing an error and if everything has gone well foreign on this function now comes the next function which is uh get books guys I'm little pressed on time okay so I'm going to be able to just finish this next function which is okay it works quickly so we'll say cat box context sorry fiber dot now a lot of people ask me why I cannot make longer videos it's because guys I upload videos every day every day single day so it's like a schedule right that I scheduled like um you know create videos every day but I have to I run my own software companies so I'm unable to provide more time than this and I try to do better but this is the max that I'm going to pull out but it's you know good to get something out rather than you know posting nothing so that's why I do this so I I stay in touch with uh the Technologies myself okay so here what we're doing is we're creating a variable called models and it's a slice of type models.com now uh this is something that we have not worked on right now it's going to be a nerd models package so don't get confused with this as of now okay what you need to be understanding is that we're still using our repository using the database inside the repository to find all the books so DB dot find okay here we're saying book models Dot edit and we can now handle this error so we'll say F error is not equal to nil we're going to say context history of status request dot Json oops so this is why I hate using extensions but you know for I use extensions for all the viewers so that's it's uh you know easier for you to understand I guess I mean a lot of people have asked me to use extensions that's right guys earlier I never used to use an extensions so could not get the books okay so if there is an error you want to say could not get the books and you want to um after this line you want to return the error because the get books function also returns another right so there's an error you'll turn an error while finding books but if everything went well you want to say context dots Paris obviously you want to say http.status okay dot Json and inside Json you'll have basically a fiber dot map and here you will have a message books fetched successfully yes and then you'll have your data which should be Equity okay and at the end you wanna I don't have perfect so what you're doing here is we have created a variable called book models and that's what we want to find because of type models.books we haven't created our models package yet that's why it's giving us a Scoopy line and you'll have to create the package we'll have to import models package and then we'll have to obviously have something called spokes as struck there but here what we're doing is we're creating a slice of stats we want to be able to basically uh send that those books as data in um as Json right as response from this API so this is why we had to create this variable because that's what we want to send right good models it's basically a collection or a list of all the books in your database and you'll use repository database dot find and you'll find book models there's an error we'll handle the error if everything went well you'll save simply say 200 and you've returned the book models and you'll send a message saying box fetch successfully now in the next video we'll work on our get book by ID function we'll work on our delete book function these two functions are remaining and then we'll also quickly take care of our storage and models pretty straightforward in the next video I think we'll be done with this little project right so uh just wanted to create this project to show you how to work with postgres with uh golang and a few people have commented that they also want to see how PG go package works with postgres fair enough I'll create a video on that and a few and one person has also commented that they'd like to see sqlc or SQL boiler with this fair enough I can show you that also not a problem uh we'll work with SQL pointer the only thing is that they get such a big layer of abstraction on your project that you don't understand where the problems happen so this is why the first thing that I recommend learning is something like this where you have to do a lot of uh work on your own with core and then we work with something like SQL boiler which kind of takes away all the work away from you it does gives you a lot of abstraction it's very easy to learn but it's something that uh you should not start with as a developer starting out using postgres for the first time with cool line okay thanks a lot for watching do subscribe to this channel I hope you're liking it I put out awesome value every single day so we'll just be working on this model's file so I will call it books dot go and this will obviously belong to package models because that's how the golang naming convention goes the name of the folder is also the name of the package models sorry uh yeah package models and when you import this package into your other files like main.go files it'll be very easy because you'll be able to import the package directly and this could have had multiple files and all would have belonged to the package models okay and we can import our package corn dot IO slash guard and uh here is where we Define our books start it will have what all can it have didn't have ID and I will have an author title and a publisher now there are a few things that you need to look at um foreign is obviously that you know you have to Define this as integer and everything else will be string [Applause] okay and here uh now I have the garm documentation open with me with gone what you can do is you can say something like this gone and you can Define your primary key so you can say primary key right and there are many such things that you can do with this gorm keyword so feel free to take a look at the god documentation and check out all the different type of keywords that you can use so I'm using primary key here but it's your homework to check out different types of other keys that you can set here right so just a hint you can also set indexes on particular fields right so this is what the Quorum keyword allows us to do and there's one more thing that it allows us to do we can also say Auto and pretty much right for the ID and Json now it will appear like this ID okay whereas author will appear like this author and title will be Json title and here it will be publisher okay so in this database right when the database the the data is created the ID will be created by the by God mode by the database itself okay these three other things author title and publisher is what we'll have to send right this is why we mentioned Auto increment because the ID is something that will be created by uh gone or the database you know because the first ID will be one then will be second third and so on whereas author title and publisher is something that we have to provide when interacting with the API okay and this is also the reason why this doesn't have a star and these all are Pointers and then I'll need a function here for migrating so um corm gives me the ability to Auto migrate in the sense uh with with mongodb you don't have to do this with mongodb you know uh you're able to easily create databases easily uh create connections on the databases and all that whereas with postgres to start with you need to have that database if you want to interact with it right it doesn't automatically create it so you can use Auto migrate function to do that uh so the function that will contain the logic for auto migration will be called migrate books and using this function basically this function is the one that I'll uh I can interact with from my other files I'll pass DB to it which is of type 1 dot DB right gorm being this package that we're talking about and reviewing uh you know a very an argument to this function of type Corner TV this function can return an error and the main line here the main thing that which is going to be the heart of this function is basically DB dot Auto migrate now we already know the DB is of type 1 right so.com.db is something that we can access here and uh that gives us gorm gives us access to this function called Auto migrate feel free to check it out I mean I recommend that you check it out in the corn documentation it's a very common thing I've used it in many other videos like even with working with isq and all we've used this automatic function very commonly used with postgres as well right because you have to have that database to be able to talk to it it's not like mongodb where even if you don't have the database you talk about the database and mongodb you will create it for you the postgres you can't do that you have to have that database so this creates the database for you uh with you know empty data as you can see it's an empty struct okay today we are talking about our storage uh folder or storage package and here let's call this file postgres.com and our main.go file we we had a reference to storage right and this basically is going to have a function called new connection which is responsible for creating the connection to the database so storage full uh folder where it's called storage and why this file is called postgres because it has all the logic to work with our postgres database okay so storage package is what we'll have to import out here and we'll also have um our config related logic out here so let's do that so let's call it packet storage and we'll import a couple of things okay and for now at least I need fmt and I obviously need because this will have logic to work with postgres so I'll obviously need my postgres let's say garm dot IO slash driver slash race now gorm has a lot of things right and amongst those things it also has the driver for postgres and that's what we're using .io now there are many ways to work with postgres and I somehow find uh gorm to be the easiest and simplest way and this is why I've shown this in this that in this video you can also use SQL boiler to work with postgres you can also have PG go and I'll cover those in upcoming uh series not as part of the series the series only is going to have gone which in my opinion is the easiest way to work with postgres but in other series I can also cover PG cover and SQL boiler okay now your config so config it's going to have your host going to have port all common things right host in the sense which uh is it localhost or is it done production Port is like 8080 or 9000 wherever you want to run and password user DB name and necessary mode so host is string technology and all of them can be basically copied and paste it because all of them are strings now comes the most important thing the new connection function which we're waiting for so we will come here it'll say funk new connection text and config how do I know that because that's what I'm passing out here I'm passing config out here so that means if I'm passing on config out here I have to also Define my config variable I'll do that soon okay take some config what is it it's of type config destruct that I've created so config argument is basically a type config and you have form dot DB comma errors okay let's take a variable called DSN let's say fmt dot printf and out here I'll say post port and then I have my password my DB name SSL mode and yeah so all these things right so for host to be able to print it out I'll have to say percentage s is equal to percentage yes and SSL mode I'll put a comma here and I'll basically uh print out these values which are going to be corresponding to these okay so I'll say config config being the argument passed to me which will have all of these values because the soft type start config right of the struct so we'll have all these values so it'll have a host which will get printed over here ahead of host which will have config dot port config.user password Dot DB name and config dot as a server all right and after this we'll have burn dot open First Press dot open command Dot config and here you'll get access to your TV video so this function the new new connection function basically returns DB which is of type gorham.tv okay and here in our migrate books function we have seen that this accepts an argument called DP which is the type go on Broad TV right so the origination of everything is out here from the new connection new connection function okay this is what this is what gives us access to god.tv the DB argument and gone dot open pack function is basically responsible for creating the connection with uh postgres so this is like Milestone zero this is where it's all originating from this is where you create the connection with postgres and how do you open open or create the connection you use all of these different things your host Port password Etc to create the connection and now we can handle the error so we'll see if error is not equal to nil errors and otherwise everything went well we'll say TV channel for the error MDB the value all right so only one small issue here is that fine we have to do a little bit of cleanup out here so we need our config let's create config so we'll say config variable is equal to Ampersand storage storage being our package that we just created in the last video storage dot conflict config being the struct that we created in the previous video and here we will say we'll have to basically uh get the value of all the things all the things being the host port and all of those things right so here we'll say host and then we'll have our port okay we'll have our password our user our SSL mode and our so for host we'll use the OS package get environment proposed over here we'll use our OS package again get environment report for password we use OS dot get environment TV underscore password and for user we'll have again OS dot care environment DB underscore user and SSL mode os.care environment here I will have OS dot get environment underscore name so put the commas where it's pending get the OS package press save okay so it's trying to save and then I'm expecting it to be able to uh as in all the extensions that I have I have now they were able to get understand that models and storage are basically these packages that I'm talking about I was going to do this manually but it's good that uh the extensions did it for me they were able to get the models and storage packages imported from the right places for you okay to get rid of these quick lines quickly what we can do is we can run go mod ID and we'll keep getting all those packages in the background okay so you don't have to worry about it what we have to worry about is in the main dot go file there need to be two more functions which is the treat book and the get book by ID so let's work on the delete book function quickly so let's come here and say funk delete book now we know it's not just a function it's actually a struct method so we'll have to say our Repository so we'll have access to the repository through r takes in context which is of type fiber Dot CDX and you will get back an error from here so here we'll Define a variable called book model which is of type model stuff box and we'll have an ID context dot params writing now the beauty with Fiverr right so let me explain to you a little bit about that so if you've seen my earlier videos where I've not used any um any framework like gin or fiber or G I've just used the HTTP package then you you had to Wrangle a lot or struggle a lot to get access to the params right it's not like you have to write a lot of stuff to access the params even though it's not complicated but there's there's work involved right but with uh context right with fiber you get very easy access to uh params which is basically ID params out here and you get access to the request and response very easily so that's basically uh so so this the fiber package or the framework as they call it the fiber framework uh and in the background is just like a layer on top of your HTTP package it's there's no magic going on right it's just giving a lot of abstraction to you but at the back end it's that's what it's all doing it's basically converting your code to uh work with the HTTP package anyhow here we'll check if ID is empty string right so I use these Frameworks like fiber gen and all that but I only use them because I know uh at the base level how to how to still build a program without using any Frameworks so if you want to be a really good golang developer you don't have to use all these third-party Frameworks and Frameworks and you should be able to build things just by using what golang gives you and that's when you'll understand things from a really deep level so you say context dot status [Applause] HTTP dot status internal server error dot Json fiber.map and here you will say message the ID cannot be empty okay so things like fiber.map things like how to access the context always have the fiber documentation open with you so whenever I'm working with let's say something external like like warm or Fiber I always have the documentation open with me right I'm not I'm never am I flying blind so that's a good practice so always when you're building programs don't try to guess don't try to use your own minds don't try to assume things just open up the documentation and actually pick up stuff from there it's not a problem it's not a problem to pick up stuff from the documentation okay uh then this delete method is you have access to R which is your repository access to DB and you will use the delete method [Applause] foreign [Applause] id id being what you received in this API and let's handle the error search error dot error not equal to many context dot status bad request and here you'll see fiber.map switch foreign [Applause] [Applause] both added oh sorry deleted successfully right l means the error so there's no error so we'll terminal for the error otherwise we have been returning error till now everywhere so book detected so successfully and in this video we are going to be working on our get book by ID function but before that before that out here we did write our migration function my great books but we never called it so we'll have to do that now so we'll say error is equal to models dot migrate box DB DB basically being the new connection so when you now look at this my get books function everything becomes clear because taking in DB right and DB was created here which is the new connection which is from this function Video Connection so you pass DB here and you handle the errors field save error is not equal to nil let's say law Dot fatal I could not activate TV all right so now the most important function which is get books by ID so come here above your setup routes function and here you can say func get book by item now as you know this is not simply a function it is a struct method so you have R and then you have Repository Logistics in context which is a type fiber dot CTX returns an error okay so firstly when we want to get a book by ID obviously need the ID and ID is going to come from Context dot parameters you have seen in the delete function okay so with fiber context you can easily access all the parameters so you'll capture that in a variable called ID let's create a book model it's a type models. bi models.books we mean this struct out here and we'll check if ID is nmp string as nothing was passing the ID and that means there's obviously a problem so we'll say context Dot status HTTP Dot status internal server errors dot Json ampersand fiber.map and your message will be ID cannot forget it and you'll say fmt dot print Ln the ID is commodity so whatever ID you've received you're just checking I'm just putting this line here to check you know if the ID is received properly or what the ID is just to be sure it's completely optional as you can put comments here you don't want to write this time it's okay but usually when I have uh an update function or a get book by ID function I usually print out the ID so that I know that you know this function is receiving the ID and everything is working perfectly so here you'll say r dot DB dot where ID is equal to question mark command ID you'll get that book so it's a book so where ID is ID the ID that you have received here in this function then you get that book okay it's a context dot stress http.status Cloud request Json this is why I hate extensions using those Gola extension guys because it tries anything tries anything that I don't want to write so you'll say fiber.map and you'll write the message [Applause] foreign and here if everything went well there was no error then you want to give a 200 status so how do you get 200 status you say context.status and this HTTP dot status okay dot Json fiber.nap and here you'll see message book ID first successfully comma data model return news okay so that completes your uh main file as well now is the time to start running our program and seeing from Postman if any issues come up before we do that I just realized that our end file is empty so here I have to create my host similar to similar to this host Port password and these basically these variables need to be there in your environment file so we'll have DB host is equal to localhost and your DP Port so your postgres usually runs on 5432 so in on my machine also it's running on 5032 you can check on your machine once it's running on user is Optical password is a new password this is my user and password that I've created on my postgres so in case you don't know how to do this there's a very easy article on digitalocean on how to set up your postgres and then go to your postgres terminal which is PA SQL and then just creating a user with password very simple and straightforward name is called fiber demo SSL mode so I've created this database as well okay and this collection or the table for books is created by migrate books for me but this database I've already created for myself Fiverr demo so I was trying to run the program with Goron main.gov and I got an issue right and that's because uh the issue that I can see why it's happening is because host and host and Port everything is okay but password and the DB name is actually coming as new pass which is supposed to have password an SSL mode is coming as fiber demo which is supposed to be my DB name so there's a mix up that's happening here and I have kind of found the issues because after host and forward should have been by user which is percentages and that's how the user will come so it's host Port user password DB name and SSL model that's how it's wrapping now if we run our program everything should be fine so it takes a uh as in it it's running as you can see right if it shows you this fiber um on the screen that means it's running okay so make sure you see this fibers screen and then we'll start now testing it on our Postman so in our Postman I have created create get all delete and delete get by ID uh already there my requests for create requests it's post and it's on localhost 8080 it's running so as you can see here it's starting on 8080 okay API slash create books now I can send the name of anything so here I've just written a very random thing but let's say author is I don't know um I'm just writing anything right now and leave it that's what just came to my mind title is the Stream publishers so you send it and it creates it says book has been added now to see that book you open up your get all and you see that earlier when I was testing this program out these books were added and now this new book didn't limit the stream blah blah has been had as well the and I know this this is id8 so what I can do is I can get this by ID so I'll just copy in paste it out here let's see what happens yeah so it gets the right book for me which is ID 8. similarly for delete also let me try and delete this book so it says book deleted successfully and when I get all I will see that the eighth book which is the grandified book it's not there so all the apis are working perfectly and the code is working perfectly with postgres reviews postgres we've used fiber and everything works perfectly and I'll put this code on GitHub as well so if you have any issues somewhere you can compare it with that and I'm always there on LinkedIn and you can connect with me or you can put a comment on YouTube if you get lost somewhere I can help you out thanks a lot for watching do subscribe to this channel because you get to see such awesome content right nowhere else on YouTube will get awesome content like this so thank you for watching and I'll see in the next video [Music]
Info
Channel: Akhil Sharma
Views: 25,664
Rating: undefined out of 5
Keywords:
Id: 1XPktts9USg
Channel Id: undefined
Length: 63min 10sec (3790 seconds)
Published: Mon Jul 25 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.