Golang REST API With Mux

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

I while love all these api service tutorial everyone does, but no one ever covers auth/Authz in a microserice environment with service validation. I wish someone would cover that.

πŸ‘οΈŽ︎ 24 πŸ‘€οΈŽ︎ u/moos3 πŸ“…οΈŽ︎ Jun 17 2019 πŸ—«︎ replies

Why is nobody that writes these writing tests? One of the primary reasons to use Golang IMO is that it makes TDD very easy. All of those postman tests could have been test-pairs.

Why is main.go the only file they build?

Why doesn't anyone show nice features like build-time vars? (server version as an example using git commit hash)

It's not using packages

None of the common code (like getting an ID) was isolated to a helper method.

No heap escape detection and use of a global without mutex and locking as the store...

πŸ‘οΈŽ︎ 30 πŸ‘€οΈŽ︎ u/CODESIGN2 πŸ“…οΈŽ︎ Jun 17 2019 πŸ—«︎ replies
Captions
[Music] hey what's going on guys in this video we're going to create a simple REST API using the go programming language and this is also going to be kind of an intro to the language and how to get things set up now I know a majority of my subscribers are JavaScript developers PHP developers Python and so on but if you're looking to learn a new language go may be a really good idea I've been studying it for a while and I really do like it I'm actually thinking of doing a course on it it's very powerful for things like Network and web applications it's incredibly scalable since it's a new language it which it was basically created to run on newer hardware it has really rich support for concurrency it's just a good choice if you're looking to learn a new language alright so with that said even if you've never written the line of golang if you understand the principles of how restful api is work then you'll be able to follow along with this just fine and like I said I'll also explain some of the the language syntax and things like that as we move along now since this is an introductory level tutorial we're not going to implement a database we will be using hard-coded mock data but it will be a full crud API we'll be able to create read update and delete books and we're going to use postman to make our request to the API alright so the point of this video was really to show you how to set up a goal in project how it works look at some basic syntax and how and show you how it works with HTTP so we can create a REST API alright so with that said let's go ahead and get started this video is sponsored by GPD host they offer a variety of affordable hosting plans with flexible billing cycles these plans include a free ssl certificate a free domain name website builder and many other services including free website migration with no downtime to find out more visit GPD host com or click the link in the description below alright so I already have go install it's very easy to install no matter what you're on Windows Mac or Linux just go to golang.org click download go and just go ahead and follow the instructions for whatever OS you're using Windows it's just a simple installer which I've already done I've already gone through all right I'll also be using Visual Studio code as my text editor which also has a really nice go extension and some go packages to help your development since I'm using Windows I'm using get bash is my terminal because I don't like the standard Windows command line and will also be using a third-party router called MUX which is very popular for the go language and to install it we just simply run this go get command alright so those are basically the tools that we'll be using so I'm going to go ahead and just open up my terminal like I said I'm using git bash so I'm gonna open that up I'm gonna run it as an administrator and we want to create a project in our go path okay so you're go pass by default is gonna be in your users slash your user name slash go directory and I just want to pull up a page real quick in the docs if we go to documents and we go to how to write go code you want to is this shows you how to structure like your big applications we're just gonna basically have one file but we want to create a directory in our go path in source github.com slash and then your user name slash and then your project alright so we're gonna go ahead and do that so let's say MK dir so make directory - P and then we're gonna use our go path variable on a sign go path slash source slash github.com slash my username which is Brad Travis e slash and then I'm gonna call the project REST API REST API alright so now I'm just gonna use the Windows Explorer to show you real quick if I go to my users folder so C drive users Brad and let's see it's not there I guess my go path wasn't set so to set my go path if your on Windows you can do export go path equals and then money sign home slash go okay and that should set it and I'm just gonna run that command once again alright so now you can see there's a folder called go we have source github calm Brad Travis II and rest API so this is our project folder so I'm gonna go ahead and I'm just gonna open this with Visual Studio code alright now like I said you should definitely install the go extension so if I click on the extensions icon you can see I already have it installed it's the one by Luke Obon there's 2.1 million downloads it's very popular and it's very very helpful as in terms of intellisense and just code hinting stuff like that so let's see what we'll do here is create a new file and we're gonna call this main dot go now once you do that if you're in vs code you'll get this drop down about different packages to help you out I'm gonna go ahead and click install all and that's going to install all these different packages which are just kind of like helpers to help you along with your development ok and as far as my terminal I'm using my integrated terminal in vs code you can go to view integrated terminal or you can just hit the control backtick and you can toggle it that way alright so we're ready to start writing go so I'm gonna do just a little introduction first so every main file you want to define package main and then we can import packages from there okay so you can kind of thing I'm going to do a lot of comparison with JavaScript and no js' you can kind of think of this as importing node packages you have local packages like HTTP and path and then you have remote packages so we're gonna import first just a package called fmt which is the formatter and this basically has a bunch of print command so we can print to the console because I just want to give you a simple example of running an app alright so in addition to this we need a function called main now in go when you define a function you need to use the func keyword so func main and we don't have to call this explicitly like that it just runs on its own and in here I'm just gonna say format our dot print Ln and then we want to just put in double quotes okay you want to use double quotes with go and we'll just say hello world and we'll save that okay so now to run this to test this file out we can go to the terminal and we can say go run and then the name of the file which is main go and you see we get hello world alright now if I want to compile this and build this out I can say go build build if I can spell it right and now if you look up here you'll see we have a REST API dot exe file okay so that simple command created an exe file from our program and to run it we can just say dot slash and then the name of the file which is rest API and it runs our file alright so that's what we'll be doing to actually run our server when we create it okay so none of this really has anything to do with the rest API I just want to give you a little introduction of how to set up a file alright now we're not going to need the formatter we're not going to use that we can get rid of that and get rid of that line but there are a bunch of other things we need to bring in so we're working with Jason so we want to bring in encoding slash Jason okay which is basically a core package we don't have to install it or anything we're gonna bring in log which will log errors and stuff like that we're gonna bring in our net slash HTTP package to work with HTTP and that's what you use to create api's and stuff I'm also going to bring in a small package called math math is actually its own package but I want to bring in Rand because when we create a book ok we're using books for our resource I want to add the ID as a random number so we're just going to use this to generate a random number and then I also want to convert that to a string so I'm going to bring in a package called STR Co and V so string convert alright and then we also want to bring in a router called MUX which is a third-party router I can't remember if I showed you that at the beginning I think I did but basically this is the github page and we can install it using this command here so let's go get - you and then the github page or the github link so I'm gonna copy that and we'll go down here and just paste that in and then once that runs and installs if I go to my go path and go to source github calm you can see we have a bunch of stuff here now but if you look we have guerilla and then MUX so that was installed in our go path so now we can bring that in by just saying github.com slash guerilla slash MUX alright so that's all of our imports I figured we just get all of those out of the way alright so now what we're gonna do is go to our main function in first thing we're gonna do in here is a knit the router the MOX router so we're gonna create a variable you can call it anything I'm going to just call it R you can call it router and we're gonna say colon equals MUX dot new router alright now if you've never worked with go before this colon equals may look a little weird and basically what this is doing it's its type and inference because go is a statically typed language like Java c-sharp typescript if you've worked with angular and typescript then you've worked with types but basically if I were to create a variable called age we could save our age yes far just like JavaScript and then we would say that this is going to be an int and then we'd set the value now there is something called type inference where we could actually just do instead age colon equals and then the value and then this is just going to look at this and see that this is an integer and it's going to give it that time so you'll see this quite a bit in going alright so now that we have our router variable what we're gonna do is create our route handlers which will establish our endpoints for our API and we do this using the router and then a method called handle func alright so in handle func it's gonna take in two things make sure you use double quotes that's one thing that threw me off because I usually use single quotes in JavaScript also semicolons you can use semicolons and go but most of the time you're not going to see them they're automatically inserted after you know when you run your code but in here we want to put our route so it's gonna be slash books actually let's do let's do slash API slash books and then second parameter is gonna be the function we want to run which I'm going to say get books okay and then we need to do dot methods because it needs to know it needs to know which type of HTTP method to use and we're gonna use a get so this will be a get request alright so let's go ahead and let's just copy this five times I think and this next one will also be a get but it's gonna call a function called get book and it's also gonna have an ID so we're gonna do slash curly brace ID and that's gonna get a single book this next one will be to API books and it's gonna be a function called create book and this will be a post request so I'm gonna change this to post alright this will be the update so this will be a put request and the function name will be update book and the endpoint is gonna be books slash and then we need the ID in there so it knows which one to update all right same thing with the delete that's gonna be books slash ID gonna call a function called delete book and then the method is going to be delete as well all right so now we have our endpoints and our route handlers now to run the server we're gonna do that in the main as well to run the server we take our HTTP package and we have a method called listen and serve so this is similar to app dot listen in node and Express ok it's gonna take in the port so we'll stay : 8,000 and then we also need to pass in the router which we gave the variable of our ok now in addition to this I'm going to just wrap it in log dot fatal that way if it fails we get a we throw an error alright remember we brought in that log package that's what you're using that for alright and that will start the server now it'll it'll throw an error now because we defined all these route handlers with functions but we don't have the actual functions yet ok but before we create the functions we're gonna actually set up our model so we're gonna go above the main and we're gonna create our strux ok so book struct and that's basically our model now a struct that should have an iron it struct is is kind of like a class it's used for object oriented programming in golang it can have it can have properties and methods it works very very similar to an es6 class or a Java or C sharp class so to define a struct we say type name it and call it book and then struct and then we're going to set our properties so we're gonna have an ID and we're gonna set that to a string and then what we want to do is set our jason so we're gonna put some back ticks and say Jason colon and then ID in lowercase so this will be the jason field that we fetch okay this is basically the property of the field or the struct and then we have the Jason field okay so what I'm gonna do here is just copy this four times we're gonna for these and then we're gonna have an ISBN okay these will all start with capitals just tap that over and then inside the Jason this will be lowercase ISBN alright and then this here will be the title of the book and then we're gonna change this to title and then down here this is gonna actually be the author so author and then this is gonna have its own struct author so we're gonna do asterisk author and change this to author okay so let's create a separate struct for the author and basically I'm just gonna have a first name and last name but you can add other stuff if you want the author's company or whatever it may be so let's say type author struct and we're gonna set let's say first name which will be a string and we'll say put in our backticks jason lowercase first name all right and then we'll do the same thing for last name this will be last name and that should be good so that's basically our model so now what we want to do is create these functions all these get books get book and so on so this one will get all books so we're gonna say func get books like that now any route handler function has to take in a response and request just like in nodejs we do app get and then we have whatever our route and then we have a function that has request response we're kind of doing that same kind of thing so we're gonna put in a variable of W here and it's gonna have a type but it's going to be a special type from the HTTP package called response writer all right and then the second parameter will be R and that's gonna have a type of asterisk HTTP dot request okay so that's kind of like our response and request so every function that we create that as a route handler has to have these two properties are these two parameters so I'm gonna go ahead and just copy that and let's just create all these I think there's five of them all right and then we'll just change them up so let's see this one here will be to get single book and this is gonna be get book instead of get books this one will be to create a new book so this one will be called create book create oops create book can't spell today and this one will be to update the book so update book and then this one will be to delete so this will be delete book like that alright so I'm gonna save this and we shouldn't have any errors now we can start the server so I'm gonna go down here and I'm gonna say go build and then we're gonna run dot slash REST API all right you see how it's just kind of staying there that's because the server is running and if I were to open up my browser and go to localhost oops localhost port 8000 we get 404 page not found because that's not a row remember our routes are slash API slash books and we get nothing and that's fine because we we have basically it's calling get books which there's nothing there alright now we're gonna add some mock data just to test things out so we're gonna go down to the main function we're gonna put this right under where we initialize the router so just say mock data and we need let's see we're gonna define a variable up up top here under where we created our Struck's and see it will put it right here and we're gonna say in it books variable as a slice book struct okay now a slice if you've never worked with goal before a slice is basically a variable length array because arrays are you need to define the length so you need to say this array is going to have five values or three values or whatever a slice however is variable so that's what we want to use so we're gonna create a variable called books we're gonna say it's of the book type or the book struct but it's also a slice because it's gonna be a collection of books all right so now we'll go down here to the main and in the main we're going to set books and we want to append to it so we're gonna use the append function and I'm just gonna put a to do right here I'll say to do implement database so we'll do that at some other point so append two books and we want a book okay so this is basically the struct kind of like a class and we want ID of one should be a string ISBN so for that I'm just gonna make something up and let's see what else it gets a title so for the title I'm just gonna say book one you just put a space here all right so we have ID ISBN in title now we want the author so author is gonna be a little different we're gonna just going to say author because it's it's own struct and then what we want to do is set it to ampersand author and in here I'm gonna put another set of curly braces and then put our first name which I'll say John and then last name I'll say Doh this should actually be capital L all right so when we're defining these you want to use your property name so the capitalized version when we output the Jason it'll be the lowercase version so that is a single book so what I'm gonna do is just copy this and we'll go ahead and just change some things here so we'll change the ID to two let's change the ISBN to just something we'll call the title book two I'll change the author I'll say Steve Smith okay so now we have some mock data so now we're gonna do is go up to let me just save this make sure we have no errors all right so I'm gonna go up to the get books and this one's gonna be really easy we're just gonna take Jason and we're gonna say new encoder so Jason new encoder and we want to pass in the response writer so that's the variable of W and then we want to do dot encode and then we're gonna pass in our books variable okay now one other thing we're going to do right above it is we want to set the header value of content type to application slash Jason or else is just going to get served as text and we can do that by taking that W and calling a header dot set and then inside here we can say we want to set the content type and we want to set it to application slash Jason all right and that's it we should be able to fetch our books fry it from what we have in here so I'm gonna save this and I'm gonna open up postman which actually don't have installed on this virtual machine so I'm gonna grab that real quick I'll say postman client I'm gonna go to get postman com grab the standalone version for Windows 64 and download that sorry about that guys I thought I had this installed alright so now that that's downloaded we'll go ahead and install it okay so I think I have an account but I'm just gonna go straight to the app and close this page out and now let's make a request actually you know what before we make the request we need to rebuild it so what I'm gonna do is stop with control see stop the server and I'm gonna say let's clear this out and I'm gonna do go build double ampersand and then dot slash rest API that way we can do both at once we can rebuild it and we can run the server alright so now let's go to postman and let's do a get request to HTTP localhost port 8000 slash API slash books and let's send and there we go so now you can see up here we have a status 200 which is good that's okay and we have our data so we have our ID 1 book and our ID 2 and you can see we have our author which is an embedded into that object with the first name and last name so that works now we're gonna move on to do the single book so it would be this get book function which is going to be a little different we're gonna still use this we want to make sure it's Jason Jason content type but we want to get the ID and the way that we get that is we're going to define a params we're going to set it mucks okay which is our router and we can use VARs and then we're gonna pass in the request so the R and this will get any params and then we basically need to loop through the books and find the one with the correct ID so let's a loop through books and find with ID so we're gonna say 4 and this is gonna look a little weird if you've never used go we're gonna say 4 underscore item and then we're going to use a range so we're gonna say equal to range books and range is used to basically loop through other data structures it could be a map or in this case a slice or something like that remember books is a slice so once we do that we want to do an if statement and we want to see if the item so item is is basically our iterator so for each books book it goes through we can access it with item and we want to check to see if the item ID is equal to the params ID okay so the ID that's in the URL if it is okay so if it is then we're gonna say Jason dot new encoder and pass in our response writer and then call encode just like we did above and the other and the other one and we're gonna just output that item the single book okay and then we want to make sure we just return from this and then we're gonna go down below the for the for loop here and say Jason dot new encoder W dot encode and then we're gonna pass in here sorry about that bang and man this is their really aggravating me and then we're gonna say amber stamp book and then some curly braces all right so this should turn just a single book so let's try it we'll save it and we'll go to our postman actually first of all we're gonna restart the server so ctrl C and then we'll run go build and our REST API again and then let's make a request I get request API books slash one and send and there we go we get our single book if we do two and send we get book 2 alright so that's all set now we want to work on creating a new book so we're gonna grab this again application Jason and we're gonna go under that and create a variable called book set it to the book struct and then we're gonna just set up an underscore equal to jason dot new decoder whoops not encode our new decoder and in here we're gonna pass in the body so we can get that from the request dot body and that we want to do dot decode and then pass in our amber sam book like that okay now what we want to do is set we need to create an ID for our new book so we're gonna save book dot ID and this is where we're going to use both of the the math rand that i brought in which actually is gone the reason it's gone is because the tools that are built in with the go extension if you're not using the packages you import then they disappear which I really don't like so we're going to make sure we bring in math Rand and also the other one was STR CO and V so string converter alright so we want those and then we'll go back down here and we're going to set the ID equal to R and and then what we can do to generate an integer is we can say int and we want to generate an integer between one and ten what are we gonna do ten billion ten million so we'll do 10 1 2 3 1 2 3 like that now this needs to be a string so we're gonna wrap this in the STR CO and V dot and then that has a method called eye TOA so this will convert an integer to a string so we make sure we want to wrap it in that so that'll create an ID now this this is um this is a mock ID this is not I'm just gonna say not safe this isn't something you'd use in production because it could it could generate the same ID I mean it's it's a you know it's very slim chance but it could and it's not something you'd want to do in production but this is just for example so now what we're going to do is say books talking about our global books variable right here and we want to set this equal to a pend because we want to add to it so we want to add on two books we want to add our single book ok and then we simply want to do this once again ok because we're just gonna output that single book except this should just be book so what should happen is it should add the book and there's no database is just gonna be adding it basically to memory and then it'll output it'll give us a response of that new book that we create so let's try it we'll save it and we'll go down and restart this let's see our dot body undefined why is that now this should actually be an upper case B all right so let's open up postman and now what we're gonna do is make a post request actually I'll open up a new tab here so we'll make a post request to localhost port 8000 slash API slash books and then we're gonna go to headers and we want to add the content type of application slash Jason and then let's go to body I'm going to choose raw and then we're gonna make a request so we're gonna put in our curly braces and eat this is Jason so the keys and the values need to have double quotes so we want an ISBN so for that I'll just put whatever and we want a title I'll say book 3 and see what else the author now let's see the author is actually gonna be its own object so we're gonna put a cut some curly braces and we'll say first name and let's just say I don't know Carol and then last name and we'll say Williams all right so hopefully this works let's go ahead and send and there we go we get a 200 response back with the new book and it's it's still gonna be in memory so if I go back and I go make a get request to API slash books there it is there's our new book right there Carol Williams book 3 all right so that's good now we're gonna work on we're gonna do the delete before we do the update all right so for the delete let's see we're gonna set the content type and then what we'll do is get the parameters okay again we need to make sure we get the ID so we're gonna say params equals we're gonna use the Mocs router call VARs and pass in our request and then we're gonna do a loop here again so we're gonna say for index item and we're gonna do we're gonna use a range to loop through the books and then we need to check for the ID so if item dots ID is equal to the params ID you can see a lot of this is very similar to what we would do in other languages when dealing with breasts api's but what we want to do is say books equals append and then we're gonna pass in books and we want the index so we're going to do colon index and then we want another parameter of books and then want to do index plus one : and then we want to do three dots like that and then break out of this loop like that okay and then just respond with this so we'll go outside of the loop and we want to pass in books so what's going to happen is it's going to delete it this particular book and then just give us a response of all the books so this here is kind of like a slice doing a slice in JavaScript if you were to loop through an array and then slice it out all right I know it's kind of a weird looking syntax and I don't really fully understand it but this will get rid of the book okay and I just realized I put this in the wrong function this should actually be in the delete all right so let's try that out so we're gonna go down here and we're going to restart it syntax error so this line here let's see what I do wrong append books colon index books index plus one dot dot dot [Music] oh I forgot my curly braces so this needs to go like that there we go all right so let's try that okay so that's running now let's go to postman and let's do a delete and let's delete our new one actually that's not gonna be there anymore because we restarted the server you'll see if I do a get we just have one and two so let's do a delete so API book slash one and send and there we go so now if I just do a get request to books let's see what we get and we just have the two because we deleted the first one all right so one more function to do and that's the update now the update is basically going to be a combination of what we did in delete and what we did in create so I'm going to copy everything we did and delete and put that in update and what we want to do is inside the four we're going to check for the ID and then we're gonna get rid of the the basically gonna slice it out and then add a new one so we'll slice it out we'll get rid of the break and then I'm gonna copy this from create book so we'll copy that and we'll put that right in here I don't know if this is the best way to do it but this is the way that I figured out I figured so and then we just want to return all right so that should update hopefully let's try it out okay so we'll go back to postman and I'll open up a new tab for this one this is gonna be a put request and we're gonna do HTTP I'm gonna do API books slash let's do two will update two and then we're gonna go to headers content type will be application Jason and then we're gonna go to body raw and let's put in here let's see I'm gonna say ISBN will change that to having a bunch of sevens I'll change the title let's just change it to updated title and then what do we have author so this will be first name say Jeff last name Thompson all right so let's see oh I figure out my comma here so hopefully this works making a put request to API book / - let's send it in and if we look down here alright so we I messed up something the ID I still have set to a random ID which I don't want where is it right here no where is it right here I don't want it set to a random idea I want it set to the ID of the params so I'll just grab this and replace this like that and then let's restart and if you guys have a better way of doing this please let me know that's fine let's see so we're gonna just let's just rerun this and there we go so now you can see the ID is still - so we updated the same one and we have updated title Jeff Thompson if I were to now make a get request to books you can see ID - updated title and Jeff Thompson so we now have a complete crud restful api so hopefully you guys enjoyed this I know it was a little long but like I said I will think about doing a part two where we can actually implement a database and then maybe even adding a front-end on to it okay but I just wanted to kind of introduce you guys to the goal language if you've never used it and show you how to use HTTP as well as the mucks router to create an easy restful api alright so thanks for watching guys please like this video if you liked it please subscribe if you're not and I will see you next time hey guys I just want to mention our sponsor GPD host so if you're looking for affordable fast and quality cpanel hosting look no further they offer many types of packages that include a free domain name free ssl certificate a website builder and more all hosting plans are completely managed and easy to work with you also get automatic weekly backups so whether you have a website to transfer or you're building it from scratch GPD hosts is a high quality solution to learn more visit GPD host com or click the link in the description below
Info
Channel: Traversy Media
Views: 267,756
Rating: undefined out of 5
Keywords: go, golang, go rest api, go lang, golang api, golang rest api, go rest, go lang tutorial
Id: SonwZ6MF5BE
Channel Id: undefined
Length: 44min 2sec (2642 seconds)
Published: Wed Jan 10 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.