Build a Microservice with Go #1 - Getting Started

Net Ninja
11 Sept 202316:19

Summary

TLDRThe video introduces using Go and the Chi web framework to build a microservice API. It starts by setting up a Go development environment, then builds a simple web server that responds "Hello World" to requests. It adds the Chi router for request routing and logging middleware for debugging. The video demonstrates handling requests and errors automatically with Chi. It sets up version control with Git and manages dependencies with Go modules. The goal is to end up with a basic CRUD microservice API connected to a database, built step-by-step over the course of the video series.

Takeaways

  • 😀 The video will teach how to build a microservice API with Go and Chi
  • 📝 Go is popular for building services like CLI tools, network apps and microservices
  • 👨‍💻 The video will walk through building an API from start to finish
  • 🛠️ Go has a rich standard library to help build web servers easily
  • 🚦 Chi router matches paths and methods like GET and POST to handler functions
  • 🔧 Logging middleware from Chi logs requests and responses out of the box
  • 📦 go.mod manages dependencies and versions using decentralized Git repos
  • 🖥️ The course is available ad-free on netninja.dev for $2
  • 💳 Or get access to all Net Ninja courses with Net Ninja Pro for $9/month
  • 👍 Don't forget to like, share and subscribe to support the channel

Q & A

  • What is the purpose of this video tutorial series?

    -The purpose is to teach how to make a microservice with Go and the Chi framework, walking through building an API microservice from start to finish.

  • What version of Go is used in the tutorial?

    -Version 1.20.5 of Go is used in the tutorial.

  • What is the go.mod file used for?

    -The go.mod file is used for dependency management in Go. It specifies the Git repo that relates to the Go project.

  • How does the tutorial application print "Hello World"?

    -It uses the fmt.Println function from the fmt package to print "Hello World".

  • What does the Chi router package provide?

    -The Chi router package provides HTTP routing functionality that conforms to Go's HTTP handler interface in the standard library.

  • Why is the 404 response seen when first testing the Chi router?

    -There were no handlers set up for the root path yet, so Chi automatically handles that and returns a 404 response.

  • What is middleware used for with the Chi router?

    -Middleware packages from Chi, like the logging middleware, can be easily added to the router using the router.Use() method.

  • How are errors handled in the Go code?

    -Errors are checked for nil values using if error syntax, and then handled in the code block, often by logging them.

  • Why is the API binary added to .gitignore?

    -Build artifacts like binaries should not be committed to git, as they can quickly add unwanted files and bloat the repo size.

  • What is a pointer in Go syntax?

    -A pointer in Go is denoted by an asterisk * and takes the memory address of a value rather than the value itself.

Outlines

00:00

😀 Introducing tutorial on building a microservice with Go

The narrator introduces himself and the guest YouTuber who will be helping to teach how to build a microservice using Go and the Chi router framework. Go is explained as a popular language for building various kinds of software including microservices.

05:01

👨‍💻 Setting up Go development environment

The steps are shown for setting up a Go development environment using Go version manager 'goenv' on Mac OS. Go version 1.20.5 is installed and tested. A new project directory is initialized along with 'go mod' for dependency management.

10:01

🎉 Creating a simple Go web server

A simple Go web server is built that binds to port 3000 and handles requests by writing 'Hello World' using the net/http package. The server is tested to confirm it returns the expected response.

15:02

🚦 Adding routing and logging with Chi router

The Chi router package is added to handle routing in a cleaner way compared to the standard library. Logging middleware is also added and can be seen when handling requests.

Mindmap

Keywords

💡microservice

A microservice is a small, independent service that works together with other services to comprise an application. The video explains that the goal is to build an API microservice with Go and the Chi framework. Microservices are popular because they allow for modular and scalable development.

💡Go

Go is an open source programming language developed by Google that focuses on simplicity, performance, and efficiency. The video uses Go to build the microservice because it works well for network applications and microservices.

💡Chi

Chi is a Go web development framework used to handle HTTP routing and middleware. It is lightweight and easy to use. The video uses Chi to handle routing for the Go-based microservice.

💡HTTP server

An HTTP server handles HTTP network requests and returns responses. Go allows creating a basic HTTP web server easily. The video builds a simple Go HTTP server to demonstrate the basics before adding more functionality.

💡routing

Routing directs incoming HTTP requests to the correct request handler based on the URL/path. The Chi router handles routing requests to the appropriate functions in a modular way.

💡middleware

Middleware sits between the raw requests/responses and the final request handler. Chi provides logging middleware out-of-the-box to log requests/responses.

💡handler

A handler processes an HTTP request and generates a response. Handlers conform to Go's http.Handler interface. The Chi router itself is an http.Handler to easily integrate with the Go HTTP server.

💡dependencies

Dependencies are third party packages used in an application. Go uses a decentralized dependency management system where packages are retrieved based on their git repository URL.

💡go mod

The go mod file tracks dependencies for a Go project. Running commands like 'go mod init' and 'go get' will add entries automatically to manage dependencies from their git repositories.

💡API

API stands for Application Programming Interface. The video builds a microservice API with create, read, update, and delete functionality to manage data.

Highlights

Go is popular for building microservices, network apps, and CLI tools

Go mod initializes dependencies and project structure

The main() function is the entry point to a Go program

Built a basic web server to use as a starting point for our API

Using the chi router because it's similar to gorilla mux

Go get vs go mod tidy - two ways to add dependencies

Chi router handles 404 responses automatically

Added middleware logging using Chi's built-in support

Commit early and often - make small commits

Buy the full course ad-free at netninja.dev

Please subscribe, share and like the videos

Go remains backward compatible across versions

HTTP handler interfaces power Chi's routing

Pointer syntax with ampersand denotes memory address

Build binaries for multiple architectures with Go

Transcripts

play00:01

or rather than gang so in this series

play00:03

you're going to learn how to make a

play00:05

micro service with go and a framework

play00:08

called Chi or Kai or however else you

play00:11

want to pronounce it and to teach you

play00:13

how to do this I've brought in the

play00:14

YouTuber dreams of code who's got a

play00:16

bunch of really nice videos about go

play00:18

python rust and other subjects as well

play00:20

his videos are all really slick and

play00:22

informative so definitely check out his

play00:24

channel the link is down below the video

play00:26

anyway without further Ado let the

play00:29

tutorial begin

play00:31

foreign

play00:33

[Music]

play00:35

programming language that Prides itself

play00:37

on being simple to use whilst remaining

play00:39

powerful and performant because of this

play00:42

go is a language that is popular for

play00:44

building many different types of

play00:45

software such as command line tools

play00:47

Network applications and microservices

play00:49

in this series we're going to walk

play00:51

through building an API microservices

play00:53

and go from start to finish by the end

play00:55

you'll learn how to spin up a basic

play00:57

microservice API which connects to a

play00:59

redis database and is responsible for

play01:01

creating reading updating and deleting

play01:04

our data type so without further Ado

play01:06

let's get started before we can begin

play01:08

writing code we'll need to make sure we

play01:10

have go installed on our system I'll be

play01:12

using Mac OS for the majority of this

play01:14

video but it should be similar in other

play01:16

operating systems as well if you head on

play01:18

over to the golang website you should be

play01:20

able to find installation instructions

play01:21

for your operating system if you're okay

play01:23

with the basic installation I recommend

play01:25

following the instructions found here

play01:27

for me however I'm going to use a tool

play01:29

called goemph which allows us to manage

play01:31

multiple versions of go on the same

play01:32

system

play01:33

so I'm going to show you how to get that

play01:35

set up

play01:36

to install goemph you can either follow

play01:38

the instructions on GitHub or use your

play01:40

operating systems package manager if you

play01:42

have one of course for Mac OS it's as

play01:44

simple as using Brew install go MV

play01:47

once go end is installed run the

play01:49

following line to ensure that it loads

play01:51

every time your terminal starts and then

play01:53

restart your terminal window you can

play01:55

test that everything is working okay

play01:56

with the following command if this

play01:58

doesn't work then you may have missed

play01:59

the step with everything set up we're

play02:01

now ready to install go what's nice

play02:03

about using go end is that you're able

play02:05

to install the same version as I am in

play02:07

this tutorial as it's very likely that a

play02:09

more recent version of go is currently

play02:10

available at the time you're watching

play02:12

this

play02:13

you're probably okay to use the latest

play02:15

version of go as the developers try hard

play02:17

to remain backwards compatible however

play02:19

there's never a guarantee of that being

play02:21

the case so feel free to use the same

play02:23

version as I am the video if the most

play02:25

recent one doesn't work

play02:27

to install go type in the following

play02:29

command this will install version 1.20.5

play02:32

after that we can run the following

play02:34

command to set the global version of go

play02:36

in go EMP finally you can test that

play02:38

everything is working correctly by

play02:40

running the Go version command which

play02:41

should print out 1.20.5

play02:44

now we're ready to start building by the

play02:47

way in case you haven't noticed I pretty

play02:48

much use the terminal for most of my

play02:50

development I also use neovin as my

play02:53

editor of choice but you may feel more

play02:54

comfortable using something like vs code

play02:56

or another graphical editor the CLI

play02:58

commands that I use in this video should

play03:00

work the same for you however and so you

play03:02

may need to jump into the terminal at

play03:04

certain points first things first we'll

play03:06

need a directory to store our project

play03:08

I'm going to create mine under projects

play03:10

slash orders API feel free to choose a

play03:13

different directory for yourself however

play03:15

once inside we now need to actually

play03:17

initialize our go project we can do this

play03:19

by running go mod init you'll need to

play03:22

add the project repo as the final

play03:24

argument this can be any git repo such

play03:27

as GitHub or gitlab here I'm specifying

play03:29

my GitHub repository additionally this

play03:32

repo doesn't need to exist at this stage

play03:34

you can always create it later and you

play03:36

can always rename this if you need to go

play03:38

mod is basically goes dependency

play03:40

management solution similar to nodes npm

play03:43

or Ruby's gems however unlike those

play03:45

systems it's actually decentralized and

play03:47

works off of git and therefore each go

play03:50

project is specified by the git repo it

play03:52

relates to after running go mod in it

play03:54

you should see a go.mod file inside of

play03:56

your project if we open this up we can

play03:58

actually see that this has our project

play03:59

repo inside of it simple stuff

play04:03

next it's a good idea to initialize git

play04:05

so that we can actually have good

play04:07

hygiene on our project and track changes

play04:08

as we go through so just run the get

play04:11

edit command to initialize our

play04:12

repository after that go ahead and add

play04:14

our initial commit which should just be

play04:16

our go mod

play04:17

once that's done open up your project in

play04:19

your editor and let's start our first

play04:21

file let's call this main.go to specify

play04:24

this is where the main function will

play04:25

live

play04:26

the first line you want to add is the

play04:28

package name in this case it's the main

play04:30

package every file in go belongs to a

play04:32

package which is how it Imports are

play04:34

organized in this case we're specifying

play04:36

that the main.go file lives in the main

play04:39

package which tells the compiler that

play04:41

our code is a program and so it builds

play04:43

an executable next we need to add our

play04:45

main function every go program has a

play04:48

main function which acts as the main

play04:49

entry point to our code AS is customary

play04:52

let's start off by printing hello world

play04:53

inside of our main function to do this

play04:55

we first need to import another package

play04:57

called fmt or format some others might

play05:00

call it thumps but I disagree

play05:03

to do this we need to call the import

play05:05

format command just underneath our main

play05:07

package

play05:08

if you have a modern editor configured

play05:10

properly Imports should be automatically

play05:12

imported for you but it's worthwhile as

play05:14

doing this manually just to see how this

play05:16

works

play05:17

next head back to the main function and

play05:19

type in format dot print line hello

play05:22

world

play05:23

you'll notice that this function is

play05:24

camel case but the first letter is a

play05:27

capital go uses this for encapsulation

play05:29

to specify that the function is public

play05:31

now our program is complete let's jump

play05:34

over to a terminal window and actually

play05:36

run this code we can do so by using go

play05:39

run and to the name of our file path in

play05:42

this case main.go

play05:45

after a short period of time you should

play05:46

see Hello World print to the console

play05:48

perfect we've just created our first go

play05:51

program congratulations

play05:53

we can also build our code by using the

play05:55

go build command converting it into a

play05:57

binary go is pretty awesome and you can

play05:59

build binaries for other architectures

play06:01

if you like however that's beyond the

play06:03

scope of this video now that we have the

play06:05

basics down let's turn it up and

play06:07

actually build a simple web server which

play06:09

we'll use as the starting point for our

play06:11

API go comes with a rich standard

play06:13

library and provides all we need to get

play06:15

a basic web server running which we can

play06:17

extend later on

play06:19

to start first add the net HTTP package

play06:22

to our Imports this package provides

play06:25

functionality for creating both HTTP

play06:27

clients and servers which is what we

play06:29

want

play06:30

now we can instantiate an HTTP server

play06:32

using the following line in our main

play06:34

function this creates a basic go type of

play06:37

HTTP server and stores it in a variable

play06:39

called server

play06:41

you'll notice we're using an ampersand

play06:42

which means we're storing this as a

play06:44

pointer and taking the memory address

play06:46

rather than the value

play06:47

inside of this type we can then Define

play06:49

some of the properties of our server the

play06:51

first is the server's address which will

play06:53

bind to Port 3000 using the given string

play06:56

next we'll need to specify a Handler for

play06:59

our server this is an interface that

play07:01

will be called when our server receives

play07:03

a request

play07:04

let's use the HTTP Handler function call

play07:07

and specify a function named basic

play07:09

Handler which we're going to create now

play07:11

to do so let's define a new function

play07:13

using the func keyword we'll call this

play07:15

basic Handler as we suggested and

play07:17

specify the following parameters which

play07:19

is what we need for a function to be

play07:21

able to conform to their HTTP Hamber

play07:23

interface

play07:24

the first parameter is called W and is a

play07:27

HTTP response writer this is an

play07:30

interface type that enables us to write

play07:31

what will eventually be our HTTP

play07:33

response the second type is called R and

play07:36

is a pointer of type HTTP request

play07:39

we can tell this is a pointer by the use

play07:41

of the Asterix this type represents the

play07:43

inbound HTTP request the server receives

play07:45

from the client inside of the function

play07:48

let's go ahead and write a body response

play07:50

of hello world

play07:51

we can do this by calling the right

play07:53

method of the response writer this

play07:55

function expects a byte array so we'll

play07:57

need to cast our string to B1 which is

play08:00

done by using the syntax on screen

play08:02

All That Remains is to actually run our

play08:04

server

play08:05

we can do this by calling the listen and

play08:07

serve method on our server type this

play08:09

method returns an error and it's good

play08:11

practice and go to handle them this is

play08:13

done by using an if error check which

play08:16

will check if the error exists I.E it's

play08:18

not nil inside of the block we can then

play08:21

handle the error which in our case we're

play08:23

just going to log it to STD out using

play08:25

the format.printline method okay now

play08:28

we're able to go ahead and test out this

play08:29

code let's jump over to a new terminal

play08:32

window

play08:33

we can run our app using the go run

play08:35

command we saw earlier once that's done

play08:37

we can open up another terminal window

play08:39

and run a curl command to our localhost

play08:41

at Port 3000 this will send an HTTP get

play08:45

request to Arc server and we can see we

play08:48

get a response of hello world which

play08:50

shows us our server is working as

play08:52

expected very nice

play08:54

to stop the server head over to the

play08:56

window where we're running it and press

play08:58

Ctrl and z

play08:59

now that we have our basic web server up

play09:02

it's time to add some additional

play09:03

functionality to it the first thing

play09:05

we're going to want to do is handle HTTP

play09:07

routing you may have noticed but we

play09:09

currently only have a single Handler in

play09:11

our project which will handle all of the

play09:13

inbound requests

play09:15

we could do some basic routing inside of

play09:17

this Handler but that can be incredibly

play09:19

tedious to do so and it's a challenge to

play09:21

properly handle things such as path

play09:22

parameters

play09:24

so whilst go does have a robust standard

play09:26

Library it's worthwhile for us to use a

play09:28

third-party dependency at this point but

play09:30

which one well my go-to router used to

play09:33

be gorilla mux which offered a great

play09:35

deal of functionality for very little

play09:37

abstraction whilst remaining true to the

play09:39

HTTP Handler interface of the standard

play09:41

Library

play09:42

however as of the end of 2022 gorilla

play09:46

mux has been archived as read only so

play09:48

for future proofing our API it's

play09:51

probably not the best choice there's

play09:53

plenty of other options out there

play09:54

however but for this video I'm gonna go

play09:57

with Chi

play09:58

this router is very similar to gorilla

play10:01

marks and also conforms to the HTTP

play10:03

interface of the standard Library so it

play10:06

works as a suitable replacement in my

play10:08

opinion to use G we first need to add it

play10:10

to our code there's a couple of ways to

play10:12

do this and they all involve using go

play10:14

mod before I show you these approaches

play10:16

now is a good time to commit our code so

play10:19

we can easily roll back any changes if

play10:21

we run git status we can see that our

play10:22

API binary currently appears in the

play10:25

untracked files that's not ideal when

play10:27

using git it's a bad practice to commit

play10:29

any build artifacts as they can add junk

play10:32

to a git repo pretty quickly

play10:34

to solve this we need to add a DOT git

play10:37

ignore let's go ahead and create one

play10:39

inside we can then specify the name of

play10:42

any file or folders We want git to well

play10:44

ignore

play10:46

let's add the name of our binary which

play10:48

is API okay great now if we run git

play10:51

status again we should see that the API

play10:53

is no longer available to be tracked

play10:55

also because we're on Mac OS it's

play10:57

probably worthwhile to also add the dot

play10:59

DS store files to our get ignore as well

play11:01

these files are created whenever you

play11:04

navigate to a directory using finder

play11:06

rather than opening up our DOT get

play11:08

ignore file again we can actually run

play11:10

the following command which will

play11:12

concatenate a string into our DOT get

play11:14

ignore file once that's done go ahead

play11:16

and run the get add command to add all

play11:18

of the files in our directory and then

play11:20

run the git commit command to store them

play11:23

now we can demonstrate the two

play11:25

approaches for adding a dependency to

play11:26

our project

play11:28

the first approach is to use the go get

play11:30

command which will download and add an

play11:32

entry to the go mod of our current go

play11:35

project provided we're in one let's try

play11:37

this by adding Qi to our project to do

play11:40

so type in the following command you'll

play11:42

notice that we're specifying the git

play11:45

repo of chi remember go mod is

play11:48

decentralized and so it uses the git

play11:50

repo URL as the package identifier now

play11:53

if we take a look at our Godot mod we

play11:55

can see that an entry has been added so

play11:58

this is the first approach however the

play12:00

second approach tends to be the one I

play12:02

use more often let's reset our changes

play12:04

to show how we would use this

play12:06

for this approach we just import the

play12:08

package into our code like we would any

play12:10

other then when we want to add it to our

play12:12

go mod we just call go mod tidy in our

play12:15

terminal this will tell go to search for

play12:17

any packages within our project and add

play12:20

them to the go dot mod as you can see

play12:22

Chi has now been added also you may have

play12:24

noticed that a go.sum file now exists as

play12:27

well this is used to ensure consistency

play12:29

across package versions in case they are

play12:31

updated Upstream it's a good idea to

play12:33

check in both the go mod and the go some

play12:36

files into our git repo so we'll do this

play12:38

now

play12:40

okay with Qi added to our project and

play12:42

our code committed let's actually use it

play12:44

with our HTTP server heading back to our

play12:47

main function we need to First

play12:48

initialize a new instance of the QI

play12:50

router for use with our server we can do

play12:52

this by calling Qi dot new router and

play12:55

assigning it to a variable called router

play12:57

in go any method prefix with the word

play13:00

new is conventionally a Constructor

play13:01

oftentimes it's preferable to use the

play13:04

Constructor method instead of directly

play13:06

instantiating an instance as they will

play13:08

often initialize private properties of

play13:10

the type with our new router created

play13:12

let's go ahead and add a root for get

play13:14

slash hello and we'll match it to the

play13:16

basic Handler that we've already got to

play13:18

find we can do this by calling the

play13:20

router.getmethod and passing in our path

play13:22

as the first parameter the second

play13:25

parameter requires an http.handler

play13:27

function which we can just set to our

play13:29

basic Handler

play13:30

the last thing we need to do is add our

play13:32

router to the server Handler what's

play13:35

really nice about Qi is that the router

play13:36

type itself conforms to the HTTP Handler

play13:38

interface so all we have to do here is

play13:41

replace our Handler with our router

play13:43

instead with that done we can go ahead

play13:45

and test our Behavior

play13:47

to do so let's rerun our app using gorun

play13:50

on our main.go file

play13:52

heading over to another terminal window

play13:54

we can then run our curl command against

play13:56

our localhost at Port 3000 however this

play13:59

time you'll notice we get a 404 page not

play14:01

found response that's because we haven't

play14:03

set any handlers for the slash root and

play14:06

she is automatically handling that for

play14:07

us which is pretty neat let's run curl

play14:10

again but this time point it to our

play14:12

slash hello path this time we get back

play14:14

the expected hello world response

play14:16

there's one last thing for us to test

play14:18

let's try this with a post request

play14:20

instead of a get request

play14:22

we can do this with curl using the X

play14:24

flag which allows us to specify the HTTP

play14:27

method make sure you set X to uppercase

play14:30

we'll also add the lowercase V flag so

play14:32

that we're able to see the full HTTP

play14:34

headers here you can see we're getting

play14:36

our HTTP status response of 405 which

play14:39

stands for method not allowed this is

play14:42

because we only specified a route for

play14:44

the method of get in our path and

play14:46

therefore Qi provides this error for us

play14:48

with a basic router added it's clear

play14:50

we're missing something and that

play14:52

something is logging

play14:54

Chief fortunately provides us a logging

play14:56

metalware that we're able to use right

play14:57

out of the box

play14:59

we can add this to our router by first

play15:00

importing the middleware package from

play15:02

the G plugin by using the following line

play15:04

with our middleware imported we can then

play15:06

add it to the router via the use method

play15:09

now if we restart our server we should

play15:11

start to see logs appear whenever we

play15:13

handle a request and response

play15:15

nice

play15:16

now that we're in a good spot it's time

play15:18

to commit our code again

play15:20

to do so go ahead and run the git add

play15:22

command to Stage our changes and then

play15:25

type in the git commit command to go

play15:27

ahead and commit them

play15:28

by the way the m flag stands for message

play15:31

in case you hadn't guessed that already

play15:32

this allows us to specify the message we

play15:35

want to store along with our actual

play15:36

commit

play15:37

by the way if you want to watch this

play15:40

entire course now without YouTube

play15:41

adverts you can do it's all up on the

play15:43

net ninja website netninja.dev you can

play15:46

buy the course for two dollars to get

play15:48

instant access to all of it or you can

play15:50

sign up to net Ninja Pro and get instant

play15:52

access to all of my courses without

play15:54

adverts as well as premium courses not

play15:56

found on YouTube including my udemy ones

play15:59

that's nine dollars a month and you can

play16:01

get your first month's half price when

play16:03

you use this promo code right here so

play16:06

I'm going to leave this link Down Below

play16:07

in the video description for you to sign

play16:09

up and I really hope you enjoy this

play16:11

series and please do not forget to share

play16:13

subscribe and like the videos that

play16:15

really helps a lot and I'm going to see

play16:17

you in the very next lesson

Rate This

5.0 / 5 (0 votes)

您是否需要英文摘要?