Intro to Go - Part 1 - HTTP basics with Go 1.22

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hi there go is a wonderful ramian language one of my favorites it's full of capabilities and it makes you really productive so I have designed this series of videos to take a feature walk through while we write a real world application but before we start I would like to agree upon some Rules of Engagement this is not the typical go tutorial so I'm not going to cover every bit of the go Syntax for these videos instead what I'm going to do is to explain the verb minimum in order to understand the examples that we are writing there is going to be some other content that is going to be released there are going to be uh some articles and an online workship feel free to use this Mater together with these videos or separate it as it suits you better if you're newb and we all have been there uh my recommendation is that you take a step further and type along with me to check that the code behaves as expected that you are able to reproduce my scenarios in your computer I'm using go 1.22 for uh this content so please take that in mind and use 1 22 or newer if you have some experience writing go feel free to ask about what happens and why am I doing the things that I do in this way and if you are a little bit more advanced and you have a lot of experience right in go probably this video is not meant for you but I will do some references to best practices all of you make the uh comments that you wish and start discussions about any of the topics that are covered in this video or that are somehow related with it the application that I'm going to write for this video is going to be a program back end that is going to store notes it's going to store notes for a note taking up in a way that it holds some metadata for each of the notes it's going to be very simple but I think it's still a realistic case for a progam we're going to start by creating in a hello world project and we do so by creating a directory which we are going to call go- intro and then changing to that directory so now that we're in this new directory go Das intro we initialize the module that is required to keep track of the dependencies and we do that by using this comma line go mode for module in it for initializing in and then you have to use something that is distinctive there something that preferably you own like in this case go uh github.com my username and then go- intro so now that I have done this I have initialized the project and I can go and open the code for this project so let's see that and this is what we see when we open Visual Studio code we have here the directory we created go- intro this go mode is a file that contains the description of the module that we initialized when we did go mode in it and this is the version of go that is being used in this case is 1.22.1 there are also some settings for visual studio code are Irrelevant in this case and I'm going to create a new file that is going to be called main.go in this file I will put the program the whole program that we're going to create in this series so what I'm going to do here is copy the program and then we're going to discuss it step by step let me get rid of this part and let's focus on the progam every file in your go code should belong to a package package is a way of organizing your code and the main package is called main so the first line in your go file should be what is the name of the package that this file belongs to so in this case this file belongs to package main then let me ignore this for a second we have this funk keyword that means let's start a function here this is what I'm am going to do Define the main function fun and the main function as in other languages as in the C languages or C++ is the entry point for your code the whole code of your application this is where your program will start running and this parenthesis means that there are no arguments being used with this function and this is the whole content of the function here I have print Ln which is a function if I leave the cursor here it says that it formats H using the default formats for these operat what it does is just brints this with a new line at the end of this string and this part here the fmt dot is that this H function belongs to this package and in order to be able to use it we need to import it and this is what we do in live three we Import fmt in order to be able to use its print Ln function so that said what we're going to do is to run this application we're going to run it and we are going to start by creating a launch. Json file this is only for visual studio code if you're doing this elsewhere if you are a proper developer and you use emac or any other editor you don't need that this is only for the purpose of using Vis Studio code and clicking here and run in the application so now that we have that I can this is what it gets created by default I'm not going to change it I'm just going to close that file and here I'm going to run this application clicking on the Green Arrow here so here I have the debug console and it should have printed this Ola canaca which is similar to hello world and is the output of our PR if you don't want to use this utility of Vis Studio code and you refer to do this by running ER the program from terminal you can go to the terminal and use go then run and then main.go for the file that we want to execute so we enter and it will print the same message to the standard output that's it the next step is going to be creating an HTTP server let me get rid of the terminal here so one of the nicest things of go is that it comes with all what is required in order to create an HTTP server in the standard library in the past if we wanted to deal with a URL depending on the HTTP ver that was used and by that I mean when you make a request it is different if you make a post request then if you do a get request or a put request you could do that but if you needed to do some work in order to process the H request and extract the verb go 1.22 has ADD the capability to deal with those automatically you just have to declare what you want to do and it is backwards comp so in the past we would have used something like G or even Gorilla Max if you have some H doing go but in this case we're just going to use the standard Library first thing that we're going to do is to declare the IP address and Port that will be used in order to listen to Connections in this case it's going to be the local host and the port number is going to be 8081 and the thing that we're going to do in order to listen to that this request is going to be a declaration of an HTTP Handler add need to the default Ms the default Ms is basically the basic instructions for routing requests in the HTTP server so what we're going to do here is declare this a handle function and let me get rid of the extra content here and as you can see here I am going to save and it adds to my imports net HTTP that is the name of this module HTTP that is used to take care of all that is needed in order to use the HTTP server that is included in the St Library here if I'm using a go one. 22 I use the verb the HTTP verb that I'm expecting and this here is the URL that I want to be listening to so the second argument for this function here is the function that will deal with this request in this case this is an anonymous function Lambda and this Anonymous function must receive an HTTP response writer that is what you are going to use in in order to send your reply and the HTTP request that is the information that has been processed and pass on to you from the HTTP server once I have declared this with this Anonymous function what I'm going to do is tell it what I want my answer to be and in this case it's going to write to this response writer let me remind you that W is a or response writer and I use w. write and this string here instead of Ola caracola I'm going to use HTTP caracola just to notice the difference this here is the conversion from a string into an array of bytes that's a casting that I'm doing here because the right requires an array of bytes rather than a regular string and that's all I need to do to describe a Handler obviously I can make it far more complex but this is like the basic Handler that you can write the next thing that is needed in order to have the HTTP server is to listen and we will be using the server address that we Define as a Conant at the beginning and here is to Define what is going to be the rotor that that HTTP handle that is taking care of all the connections in this case where because I say Neil is going to use the default one that is the one that has been configured using this function this function will run and start listening on this port and in case any error happens it will return an error so instead of just leaving the function like that what I'm going to do is to take this function and replace it I'm going to attend to the error here and I'm going to log the error if it happens so I'm taking the output of this function of the HTTP listed and serve and whatever the error is I'm going to log it and I will log it as fatal because it it has stopped my HTTP server from running it might be considered a fatal error is not always the case but for now we will use it as such now that we have have this we can compile and run so let's do this using our play button as we did before and once we have this changing color we can come back to the terminal and here I could use go around main go but I'm using the play button and what I'm going to do is use curl curl is a common line utility in case you don't know it that allows you to send custom HTTP request in this case I'm sending an HTTP request to the root URL The Local Host is 127.0.0.1 the address that I use as a constant in the program and this Dash I means that it will print the headers for the response so I'm going to enter this and it says hey I got an okay from the h TP server this is the Header information basically is telling me the time the number of characters in the header and the format for the response and this is the message that I was expecting because this is what I put in my HTTP hard cool by the way if you want to stop your program from running you have to go to the red square up here and liquidate and it should stop your PR finally we would like to see what happens when we exchange some data from the HTTP client which could be a browser but in this case it's not and the HTTP server that we are running from our go program the thing that we're going to do is to close terminal come back to our code and we are going to declare here we were using an anonymous function to define the Hower but it is far more maintainable to create a function that does that so this is not going to be anonymous anymore I'm I'm going to create a new Hower function that is going to contain what I want it to happen when I create a note let me remind you that the purpose of this program is to deal with notes and we are going to create a note by invoking this H same thing we're taking an HTTP response writer and an HTTP request and we will be getting the information from the request and then writing our response to the response writer that's it so in order to exchange data you have to know what is the format of the data that you want to exchange and we're going to do this here we're going to declare a struct that is going to contain the data that our notes are going to have in this case a note is going to be stract this is how you declare stct in go you say type the name of the struct struct and then the fields the reason why note title and text the all star with capital earners is because I want them to be readable that I want it to be exported to the functions so that is similar to using a public or a pub attribute for a field or for a stct in other languages so here I have this note and it has two FS one is the title of the note note the other one is a text and what I'm going to do is make it a little bit more complicated and replace this note with something that is far more complicated not a little bit this note is similar to what we had before it still has a title which is a string still has a text which is a string but it has two more Fields the first one is a series of TXS it may be empty may have no tax or it might have more than one tax it's a string it's a multivalued field and the other one is a scope the scope has been declaring this other struct here and this struct is saying this scope struct contains a project which is also string and an area which is also string so when I declare a note I expect to have a project and an area but they belong to the same embedded structure okay so that sounds like some organization of the data and this is what I'm planning to use here to exchange data let me go back to the hler that I have declared and here I'm going to declare a function that will contain the note once it has been exchanged the goal is to send a note from the request to the server and then use this server as if it was declared as a go object so what I'm planning to do here is to use the Ability that is provided by the standard Library also to this serialized information and the data is going to be exchanged as it is in many HTTP requests as Json so what I'm going to do is to use this capability to De code Json in our code so here I create a new decoder that will use the body the r is for the request and the dot body is the part of the request that corresponds to the body of the request when you exchange some data between the HTTP client and HTTP server there are headers but there is a body the body is usually where you put the data and here it is complaining because I haven't imported Json yet so I'm going to do that right away and if we go up here you will see that now we have encoded slash Json and Json is not in red anymore the reason why we get note at the codor in Red is because we have declare both but we are not using it and go is a very picky language in those terms it wants you to declare things that you use only so now that we have declared the encoder and created it we are going to use it and it won't complain anymore about those things about not using note or the decoder because what I'm going to do is use the decoder to decode and it's going to read the data from the body and it will store the data it will deserialize the data into this note instance that I created up here this ENT is a reference to the note that I'm going to use that one and you can change the values in that one I don't want you to copy the value I want you to use this placeholder to put the data that you extract from the serialized data this are here here is going to tell me if anything went wrong if all went well it will be a nil but if I got any error it will have a value and I will have to act on that so let's replace this I'm going to copy down and remove the first one here so as you can see this and this are exactly the same what I'm doing now is I'm using the error that I got I use a semicolon and then I do the comparison check if error was nil if it was not nil which means there was an error then I want something to happen and what is that well what I want to happen is that I will use an error and this HTTP error is also a function that is provided by the standard library and I will write this error to the response writer and the value of the error will be whatever was returned from this decode and the https status will be bad request because I couldn't deserialize whatever was passed to me from the HTTP client once I've done that I return because there's nothing more for me to do here but if everything went well and I didn't get an error when the coding the data then I'm going to do something different I'm going to use fmt again the same package that I was using to print Ola caracola and here I'm going to use another function this F at the beginning means that I'm going to use a writer and this writer is going to be the same response writer I was using before and this is the format string similar to C but a little bit more robust and it allows me to print the values of the entities that I have here and this plus is to use the names of each of the attributes of these instance preceding the values so let me summarize I have this Handler that takes a writer to write the response a reader a request that contains the data that has been passed from the h client then I Define a note I create a decoder that is using the body from the request and then I decode the data into that note if there is an error then I print the error and I set the status to explain that there was an error here but if there was no error then I will print to the HTTP holder so as a response to the HTTP client the value that was sent onto me and now that I have this I'm going to use this handle and I'm going to do it declaring it before I start listening and serve and that is going to be here and I do it exactly the same as I was doing before so I use the same format HTTP handle Funk but in this string I'm using a different URL so the URL is going to be slash nodes and the HTTP verb is going to be post is not going to be a get anymore then the handle function is not going to be anonymous but it's going to be this function that I have declared down here and that should be it we should be ready to run it so let's do that we're going to run this click on the green button here and it should be running now we open the terminal here and we could run this with go run M go if you're not using Vis Studio code capability to do that so but what we're going to do here is to send data to the URL initially we're going to send empty data data so what I'm saying here is use Curl as the HTTP client print the headers the x is for the HTTP perb in this case it's going to be post and if I don't use post it won't go to that Handler that I created and the address is going to be the same one I was using before and the URL is notes like the complete the end point rather is going to be slash notes and if I do that notice that there's no data so when I enter this I get a bad request because there was no data there was nothing that could be decoded and I get an ano file here but if I create a different request in this case I put some data in and the uh uh dashd is to ER Express the data that I have here and this is the encoded Json that I want to send to the other side so I have a title which is master plan then I have some tax this is an array of a couple of things then the text of the note that I'm using and the scope that was the embedded object that I was using here inside of this embedded object I have each of the fields that I declare so the project is going to be wall domination and the area is going to be a strategy the URL same one so we run this and in the response we get this printed which is exactly the representation now not as as a Json representation but rather the printed version of the go structure that was used for the serializing the data so fully s sux we stop the go and that's it for this session in this video we have learned how to write a basic HTTP server from scratch using the standard Library only we have also learned how to add end points to that HTTP server and how to reply in different ways depending on the HTTP verb that is used also we learn how to decentralize data that is sent through the request so we can use it in the backend in the next episode we will be using this data that has been distalized in order to persist it in mongodb alas so stay curious hack your code and see you next time [Applause]
Info
Channel: MongoDB
Views: 1,329
Rating: undefined out of 5
Keywords: VI, MongoDB Atlas, Go, Awareness, Developer, Introductory, DA
Id: biaEuu57mbs
Channel Id: undefined
Length: 26min 48sec (1608 seconds)
Published: Fri Apr 12 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.