Building Microservices with Go
source: https://www.youtube.com/watch?v=VzBGi_n65iU&list=PLmD8u-IFdreyh6EUfevBcbiuCKzFk0EW_&index=2
Notes
- episode 1
http.HandleFuncregisters the handler function for the given pattern in the DefaultServeMuxhttp.ListenAndServelistens 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.NewServeMuxcreate a serve mux if you don't want to use default onehttp.Servercreate server with custom config likeIdleTimeoutgo func()to run server in goroutinemake(chan os.Signal, 1)to make channel for signals andsignal.Notifyto send shutdown signalshttp.Server.Shutdownto gracefully shutdown when a signal is sent to the signal channel
- episode 3
- create a
datapackage to organize code for data json.NewEncoderto efficently write json- use
tagsto control what json fields a written and what their names are - check method before ServeHTTP in product handler
- create a
- episode 4
json.NewDecoderto turn json into structr.URL.Pathto fine the /path after the url of the api that's hitstrconv.Atoito convert string into an int
- episode 5
github.com/gorilla/muxframe 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.WithValueandr = 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/v10for 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