Building Microservices with Go
source: https://www.youtube.com/watch?v=VzBGi_n65iU&list=PLmD8u-IFdreyh6EUfevBcbiuCKzFk0EW_&index=2
Notes
- episode 1
http.HandleFunc
registers the handler function for the given pattern in the DefaultServeMuxhttp.ListenAndServe
listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections
- episode 2
- organize project by moving handlers to their own package
http.NewServeMux
create a serve mux if you don't want to use default onehttp.Server
create server with custom config likeIdleTimeout
go func()
to run server in goroutinemake(chan os.Signal, 1)
to make channel for signals andsignal.Notify
to send shutdown signalshttp.Server.Shutdown
to gracefully shutdown when a signal is sent to the signal channel
- episode 3
- create a
data
package to organize code for data json.NewEncoder
to efficently write json- use
tags
to control what json fields a written and what their names are - check method before ServeHTTP in product handler
- create a
- episode 4
json.NewDecoder
to turn json into structr.URL.Path
to fine the /path after the url of the api that's hitstrconv.Atoi
to convert string into an int
- episode 5
github.com/gorilla/mux
frame work for serverssm.Methods(http.MethodGet).Subrouter()
create subroutes for different methodsputRouter.HandleFunc("/{id:[0-9]+}", ph.UpdateProduct)
define path variables with regexvars := mux.Vars(r)
andvars["id"]
: get variables from path that gorrilla parsed in handlerspostRouter.Use(ph.MiddlewareProductValidation)
add middleware to a routerctx := context.WithValue
andr = r.WithContext(ctx)
: update the request with context in middlewareprod := r.Context().Value(KeyProduct{}).(*data.Product)
get variable from request context in main handler
- episode 6
github.com/go-playground/validator/v10
for validating structsvalidate:"required"
tags to add to struct which will make sure the field will be validated by a funcvalidate.RegisterValidation("sku", validateSKU)
to register custom validation function- add validation step to middleware