Intro to Go - Part 2 - HTTP Servers Persisting Data in MongoDB

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi there in our last episode we explore how to write a very simple HTTP server using go we also learn how to exchange data from an HTTP client and how to deserialize the data that was coming from it but exchanging data is worthless unless we have some way to persist that data in this episode I'm going to show you how to receive this data and store it into mongodb cluster I'm going to use mongodb to purist the data in this project I have created a cluster the name of the cluster is notekee keeper and it is inside of this organization and within this project you can use any name you wish the important part is that you have access to a cluster I have created a free cluster and if you don't know how to do that please use the link that is included in this video in order to create your own free cluster now that we have created the cluster please verify that you have a user that has access to the database and also that your IP address is included so you can access it from wherever you're running this application finally we're going to go to the database here and get the connection string that is done clicking on the connect button and then on the drivers option here it tells me how to use H how to install the package that we need in order to access the mongodb driver from in this case go but there are all languages and also we have here the connection string that we need to copy it is important that you know the password for that user that you created and you replace it when you use this connection string it will be the driver that uses this connection string to access the data in our cluster let's go with the code our starting point is going to be the code that we wrote for the last episode this is a very simple HTTP server that uses two HTTP handers the first one is for the root URL with a get method and it's implement Ed as an anonymous function that just writes HTTP caracola to the client second one is implemented as a proper function here and what it does is this serializing the data that comes from the HTTP client into the types that I have defined previously and brings them back to the client so these types are the note which in turn contains a scope and that's it so now that we have reviewed this code let's go to the go mode file that that is where the name of the project is uh declared and the version of the go language that we are using there's nothing else here yet because we were basically using the code in the go standard library but now we are going to use the mongodb driver and in order to do that we're going to type this command here that brings the mongodb driver package into our code so notice that when when I tap enter I add in the go mode all these dependencies most important one here is the mongodb driver but these other ones are transitive dependencies that are required by the mongod TV driver to do its job so we can close the console now and get rid of the go mode and I would like you to notice also that there is another file that has been added here this file contains H hashes for all the dependencies so in in case something happens something changes it will act accordingly so that's basically it let's go back to the code and let's have a variable that we will be using to connect to mongodb that variable is going to be a global variable and that is not a best practice let me tell you straight because what you would like to do is to create a type that contains all your dependencies and then implements HTTP harder so it is used as an HTTP server but in this case we're going to simplify it and we're going to declare this Global variable here let's add some space here and we are going to add manually the Imports here so it doesn't complain about mongodb not being available let's so this is what we have now the mongodb driver and it is going to be used in order to access mongodb as an mongodb client this Global variable we have to initialize it we have to connect to the mongodb alas cluster and we're going to do it right after printing hello and before we initialize our HTTP server so let's add this code here and we could do it as a short variable initialization but if that is the colum equals here which doesn't require to declare the variables before but if we do that error would be perfectly fine because we haven't defined any error in this scope the mongodb client the MDB client will be H created on top of the other one it will overwrite the mongodb client that is global it will create one for this scope and this is not what we want so what we're going to do instead is use regular variable and we're going to use it like that so this should be the Declaration of the error variable and then with a regular setting we add set the mongodb client and the error as the output of the connect function notice that this function returns two values not just one so this is what we are going to use here okay if we take a look at the arguments that are required here and just by hovering the mouse on top of the connect function we notice that there is a context that has to be passed onto this function and also some options let's start with the context the context is going to be theine here here and a context is what is required to send data to the request and also to communicate when things end and in this case we are going to use a a context background we could even add a timer here to um be able to ensure that this doesn't take longer than expected but we are not going to do this for this example the next thing that we want to do is to have the connection string from our server and the connection string is is what we got from the web interface and we're going to put that here so let's define this connection string please don't use this one not because of my user and my password that I'm going to delete right after recording this video but because you won have access to this cluster it has to be your own connection string so you should Define it with the value that is provided by the web interface of your cluster it is not a best practice either to use the connection string and hardcoded here a better option would be to pass it as an environment variable and then you would set it from the outside in order to get access to this connection string and now that we have both parameters what we are going to do is to replace this implementation with the proper one so now we're going to have the context defined the error decare and we're going to use the context as the first parameter and the options client with this URI this connection string that we declare in order to connect to mongodb addas so let's add some space here and here and that should be enough to access the mongodb cluster if this goes well then we will have to the ability to send data and receive data from the mongodb atas cluster but what happens if anything go go wrong well we have to check the error variable in order to be sure that we act if that happens and what we're going to do is to basically say here that if error wasn't nil then we want to print that error to the standard errow output and exit from our program that is what log fatal does so we're going to do that and that's it so that is what we should do if anything goes wrong but what do we do if anything if everything went fine well the first thing that we want to ensure is that if everything went fine we want to be able to ensure that this connection is closed properly and we are going to do so by using a defer function here I'm declaring a defer function that is used as an statement and it uses this Anonymous function to tell the compiler what want to happen when this main function finishes and here what I'm doing is if I'm getting an error from the disconnect that is what I want to do then I will panic but basically the goal here is to disconnect from the mongod DB cluster with that done in the main function now we can use this mongodb client in our HTTP handers and we're going to do that in the create node that we have here so what we are going to do in in this Handler is to get access to a collection which is similar to what a table would be in a relational database we are going to do it right after deserializing the data so here we're going to put this snippet which is uh using the mongodb client to access the cluster that we have created notekee keeper and inside of that cluster inside of the that database we are going to access the collection which is going to be called notes and I said is going to be called because it doesn't exist at the moment this database was empty we have just created the the cluster and there is no data inside of the cluster at this moment notice that contrary to what you would do in a relational database there's no schema that you have to set before you are able to access a collection or a table in the case of a relational database and that is because there's no constraint on what are the fields that are going to be required in the documents that we store in notes at least not yet we can set them but we are have decided not to initially so we can store any kind of document with any attributes any uh arrays any fields that you want now that we have access to this collection we're going to have a command to insert the note that we deserialize from the request and we're using the context that was pass on to us through the request from through the HTTP request so if the request is canceled we will know and we will also cancel the conversation with mongodb alas we are getting two things here two one is the result of inserting the note in the database and the other one is an error and what we are going to do first as we usually do is check if there was any error Happening Here so basically I check if there is an error if there is then I return an HTTP error and then the error of the database and I set the status to internal server error could be something else but for now this is good enough and one thing that is also not a best practice is to share theor of the database with the client probably you are leaking too much information here so you better know what is happening and then send a custom error to the client in any case case we have to do this before we write to the response writer and that is because once you do the first writing to the response writer the heer has been written and there's no way to set it the values of the heer particularly the in this case the status to anything else so we do a error handing at the beginning and we do the the return in case something uh goes wrong because we don't want to continue but if everything went fine then we return the type of the value of the node that has been deserialized as we were doing before and also we're going to log the ID of the object that we have created okay so notice that there are a couple of errors here I'm going to solve those and then I'm going to compile and execute the errors that we get here are basically that I forgot importing the context so I'm going to import context and same thing for for the mongodb options now I don't have any errors and I'm going to try to run this code so I click on the play button and hopefully I will have my program running here now I'm going to open the terminal and here I could have run uh the pram with go run main go in this case I'm not doing that uh but what I'm going to do is to use the same curl command that I did in the previous episode to send this value to the database and you will see that the data appears in the database right away so basically I'm going to enter that here I get an HTTP okay and that is the value that I have here and if we go to our database then we click on browse connections and here I have the note keeper database with this collection that has been just created and here I have the data that I sent from the HTTP client to the server the program Ino that we wrote and as you can see all the values are here this is the master plan this is H the the data that we have in the text the two TXS that we have and the scope which is an embedded object here in this video we have learned how to create a connection from our pram written in go to mongodb Alas cluster and how to store data and how easy is to connect to a collection because we don't need any prior schema defined in order to talk to the database I hope you enjoyed the code that we wrote today in the next video we're going to talk about concurrency meanwhile stay curious hack your code see you next time
Info
Channel: MongoDB
Views: 416
Rating: undefined out of 5
Keywords: VI, MongoDB Atlas, Go, Awareness, Developer, Intermediate, DA
Id: D57rr3oly1c
Channel Id: undefined
Length: 15min 28sec (928 seconds)
Published: Tue Apr 23 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.