Build a Microservice with Go #1 - Getting Started

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
or rather than gang so in this series you're going to learn how to make a micro service with go and a framework called Chi or Kai or however else you want to pronounce it and to teach you how to do this I've brought in the YouTuber dreams of code who's got a bunch of really nice videos about go python rust and other subjects as well his videos are all really slick and informative so definitely check out his channel the link is down below the video anyway without further Ado let the tutorial begin foreign [Music] programming language that Prides itself on being simple to use whilst remaining powerful and performant because of this go is a language that is popular for building many different types of software such as command line tools Network applications and microservices in this series we're going to walk through building an API microservices and go from start to finish by the end you'll learn how to spin up a basic microservice API which connects to a redis database and is responsible for creating reading updating and deleting our data type so without further Ado let's get started before we can begin writing code we'll need to make sure we have go installed on our system I'll be using Mac OS for the majority of this video but it should be similar in other operating systems as well if you head on over to the golang website you should be able to find installation instructions for your operating system if you're okay with the basic installation I recommend following the instructions found here for me however I'm going to use a tool called goemph which allows us to manage multiple versions of go on the same system so I'm going to show you how to get that set up to install goemph you can either follow the instructions on GitHub or use your operating systems package manager if you have one of course for Mac OS it's as simple as using Brew install go MV once go end is installed run the following line to ensure that it loads every time your terminal starts and then restart your terminal window you can test that everything is working okay with the following command if this doesn't work then you may have missed the step with everything set up we're now ready to install go what's nice about using go end is that you're able to install the same version as I am in this tutorial as it's very likely that a more recent version of go is currently available at the time you're watching this you're probably okay to use the latest version of go as the developers try hard to remain backwards compatible however there's never a guarantee of that being the case so feel free to use the same version as I am the video if the most recent one doesn't work to install go type in the following command this will install version 1.20.5 after that we can run the following command to set the global version of go in go EMP finally you can test that everything is working correctly by running the Go version command which should print out 1.20.5 now we're ready to start building by the way in case you haven't noticed I pretty much use the terminal for most of my development I also use neovin as my editor of choice but you may feel more comfortable using something like vs code or another graphical editor the CLI commands that I use in this video should work the same for you however and so you may need to jump into the terminal at certain points first things first we'll need a directory to store our project I'm going to create mine under projects slash orders API feel free to choose a different directory for yourself however once inside we now need to actually initialize our go project we can do this by running go mod init you'll need to add the project repo as the final argument this can be any git repo such as GitHub or gitlab here I'm specifying my GitHub repository additionally this repo doesn't need to exist at this stage you can always create it later and you can always rename this if you need to go mod is basically goes dependency management solution similar to nodes npm or Ruby's gems however unlike those systems it's actually decentralized and works off of git and therefore each go project is specified by the git repo it relates to after running go mod in it you should see a go.mod file inside of your project if we open this up we can actually see that this has our project repo inside of it simple stuff next it's a good idea to initialize git so that we can actually have good hygiene on our project and track changes as we go through so just run the get edit command to initialize our repository after that go ahead and add our initial commit which should just be our go mod once that's done open up your project in your editor and let's start our first file let's call this main.go to specify this is where the main function will live the first line you want to add is the package name in this case it's the main package every file in go belongs to a package which is how it Imports are organized in this case we're specifying that the main.go file lives in the main package which tells the compiler that our code is a program and so it builds an executable next we need to add our main function every go program has a main function which acts as the main entry point to our code AS is customary let's start off by printing hello world inside of our main function to do this we first need to import another package called fmt or format some others might call it thumps but I disagree to do this we need to call the import format command just underneath our main package if you have a modern editor configured properly Imports should be automatically imported for you but it's worthwhile as doing this manually just to see how this works next head back to the main function and type in format dot print line hello world you'll notice that this function is camel case but the first letter is a capital go uses this for encapsulation to specify that the function is public now our program is complete let's jump over to a terminal window and actually run this code we can do so by using go run and to the name of our file path in this case main.go after a short period of time you should see Hello World print to the console perfect we've just created our first go program congratulations we can also build our code by using the go build command converting it into a binary go is pretty awesome and you can build binaries for other architectures if you like however that's beyond the scope of this video now that we have the basics down let's turn it up and actually build a simple web server which we'll use as the starting point for our API go comes with a rich standard library and provides all we need to get a basic web server running which we can extend later on to start first add the net HTTP package to our Imports this package provides functionality for creating both HTTP clients and servers which is what we want now we can instantiate an HTTP server using the following line in our main function this creates a basic go type of HTTP server and stores it in a variable called server you'll notice we're using an ampersand which means we're storing this as a pointer and taking the memory address rather than the value inside of this type we can then Define some of the properties of our server the first is the server's address which will bind to Port 3000 using the given string next we'll need to specify a Handler for our server this is an interface that will be called when our server receives a request let's use the HTTP Handler function call and specify a function named basic Handler which we're going to create now to do so let's define a new function using the func keyword we'll call this basic Handler as we suggested and specify the following parameters which is what we need for a function to be able to conform to their HTTP Hamber interface the first parameter is called W and is a HTTP response writer this is an interface type that enables us to write what will eventually be our HTTP response the second type is called R and is a pointer of type HTTP request we can tell this is a pointer by the use of the Asterix this type represents the inbound HTTP request the server receives from the client inside of the function let's go ahead and write a body response of hello world we can do this by calling the right method of the response writer this function expects a byte array so we'll need to cast our string to B1 which is done by using the syntax on screen All That Remains is to actually run our server we can do this by calling the listen and serve method on our server type this method returns an error and it's good practice and go to handle them this is done by using an if error check which will check if the error exists I.E it's not nil inside of the block we can then handle the error which in our case we're just going to log it to STD out using the format.printline method okay now we're able to go ahead and test out this code let's jump over to a new terminal window we can run our app using the go run command we saw earlier once that's done we can open up another terminal window and run a curl command to our localhost at Port 3000 this will send an HTTP get request to Arc server and we can see we get a response of hello world which shows us our server is working as expected very nice to stop the server head over to the window where we're running it and press Ctrl and z now that we have our basic web server up it's time to add some additional functionality to it the first thing we're going to want to do is handle HTTP routing you may have noticed but we currently only have a single Handler in our project which will handle all of the inbound requests we could do some basic routing inside of this Handler but that can be incredibly tedious to do so and it's a challenge to properly handle things such as path parameters so whilst go does have a robust standard Library it's worthwhile for us to use a third-party dependency at this point but which one well my go-to router used to be gorilla mux which offered a great deal of functionality for very little abstraction whilst remaining true to the HTTP Handler interface of the standard Library however as of the end of 2022 gorilla mux has been archived as read only so for future proofing our API it's probably not the best choice there's plenty of other options out there however but for this video I'm gonna go with Chi this router is very similar to gorilla marks and also conforms to the HTTP interface of the standard Library so it works as a suitable replacement in my opinion to use G we first need to add it to our code there's a couple of ways to do this and they all involve using go mod before I show you these approaches now is a good time to commit our code so we can easily roll back any changes if we run git status we can see that our API binary currently appears in the untracked files that's not ideal when using git it's a bad practice to commit any build artifacts as they can add junk to a git repo pretty quickly to solve this we need to add a DOT git ignore let's go ahead and create one inside we can then specify the name of any file or folders We want git to well ignore let's add the name of our binary which is API okay great now if we run git status again we should see that the API is no longer available to be tracked also because we're on Mac OS it's probably worthwhile to also add the dot DS store files to our get ignore as well these files are created whenever you navigate to a directory using finder rather than opening up our DOT get ignore file again we can actually run the following command which will concatenate a string into our DOT get ignore file once that's done go ahead and run the get add command to add all of the files in our directory and then run the git commit command to store them now we can demonstrate the two approaches for adding a dependency to our project the first approach is to use the go get command which will download and add an entry to the go mod of our current go project provided we're in one let's try this by adding Qi to our project to do so type in the following command you'll notice that we're specifying the git repo of chi remember go mod is decentralized and so it uses the git repo URL as the package identifier now if we take a look at our Godot mod we can see that an entry has been added so this is the first approach however the second approach tends to be the one I use more often let's reset our changes to show how we would use this for this approach we just import the package into our code like we would any other then when we want to add it to our go mod we just call go mod tidy in our terminal this will tell go to search for any packages within our project and add them to the go dot mod as you can see Chi has now been added also you may have noticed that a go.sum file now exists as well this is used to ensure consistency across package versions in case they are updated Upstream it's a good idea to check in both the go mod and the go some files into our git repo so we'll do this now okay with Qi added to our project and our code committed let's actually use it with our HTTP server heading back to our main function we need to First initialize a new instance of the QI router for use with our server we can do this by calling Qi dot new router and assigning it to a variable called router in go any method prefix with the word new is conventionally a Constructor oftentimes it's preferable to use the Constructor method instead of directly instantiating an instance as they will often initialize private properties of the type with our new router created let's go ahead and add a root for get slash hello and we'll match it to the basic Handler that we've already got to find we can do this by calling the router.getmethod and passing in our path as the first parameter the second parameter requires an http.handler function which we can just set to our basic Handler the last thing we need to do is add our router to the server Handler what's really nice about Qi is that the router type itself conforms to the HTTP Handler interface so all we have to do here is replace our Handler with our router instead with that done we can go ahead and test our Behavior to do so let's rerun our app using gorun on our main.go file heading over to another terminal window we can then run our curl command against our localhost at Port 3000 however this time you'll notice we get a 404 page not found response that's because we haven't set any handlers for the slash root and she is automatically handling that for us which is pretty neat let's run curl again but this time point it to our slash hello path this time we get back the expected hello world response there's one last thing for us to test let's try this with a post request instead of a get request we can do this with curl using the X flag which allows us to specify the HTTP method make sure you set X to uppercase we'll also add the lowercase V flag so that we're able to see the full HTTP headers here you can see we're getting our HTTP status response of 405 which stands for method not allowed this is because we only specified a route for the method of get in our path and therefore Qi provides this error for us with a basic router added it's clear we're missing something and that something is logging Chief fortunately provides us a logging metalware that we're able to use right out of the box we can add this to our router by first importing the middleware package from the G plugin by using the following line with our middleware imported we can then add it to the router via the use method now if we restart our server we should start to see logs appear whenever we handle a request and response nice now that we're in a good spot it's time to commit our code again to do so go ahead and run the git add command to Stage our changes and then type in the git commit command to go ahead and commit them by the way the m flag stands for message in case you hadn't guessed that already this allows us to specify the message we want to store along with our actual commit by the way if you want to watch this entire course now without YouTube adverts you can do it's all up on the net ninja website netninja.dev you can buy the course for two dollars to get instant access to all of it or you can sign up to net Ninja Pro and get instant access to all of my courses without adverts as well as premium courses not found on YouTube including my udemy ones that's nine dollars a month and you can get your first month's half price when you use this promo code right here so I'm going to leave this link Down Below in the video description for you to sign up and I really hope you enjoy this series and please do not forget to share subscribe and like the videos that really helps a lot and I'm going to see you in the very next lesson
Info
Channel: Net Ninja
Views: 46,501
Rating: undefined out of 5
Keywords: go, golang, go lang, go tutorial, goland tutorial, go chi, chi, chi router, go microservice, chi tutorial
Id: wpnN3RIRSxs
Channel Id: undefined
Length: 16min 19sec (979 seconds)
Published: Mon Sep 11 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.