This is a creation in Article, where the information may have evolved or changed. GERGELY Nemeth In recent years, Kubernetes has been the first choice for container orchestration and management platforms. For me, I also wanted to figure out how the bottom of it worked, so I decided to learn the language of Go. In this article, I will be based on my experience and from the perspective of a node. JS engineer. So I will pay particular attention to:-Dependency management-how to handle asynchronous operations let's get started:) # # What is Go?> go is an open-source programming language that makes it easy to construct simple, reliable and efficient software. -Golang.orggo was released by Google's Robert Griesemer, Rob Pike, and Ken Thompson in 2009. It is a statically typed compilation language that has a garbage collection mechanism that handles asynchronous operations based on the CSP concurrency model. Go also has the syntax of class C: "' Gopackage mainimport" FMT "Func Main () {FMT. Println ("Hello World")} ' Install go: official Guide Link: https://golang.org/doc/install.## Go dependency Management If you're going to write a lot of JavaScript code, the first problem is to rely on management issues. , how does Go deal with it? There are two ways:-Go GET-DEP in NPM terminology, you can think of them as: use go get when you need to use NPM install-g, and then use DEP to manage dependencies for different projects. To install DEP, you can install it via go get, using the following command: "Go get-u github.com/golang/dep/cmd/dep" However, using go get has a disadvantage--go get does not handle version, it is just to get Git The latest version of the Hub warehouse. This is why it is recommended that you install and use DEP. In the case of a MAC system, DEP can also be installed with the following command: ' gobrew install Depbrew upgrade dep ' (for other operating systems, see: https://golang.org/doc/ Install) Once DEP is installed, you can use **DEP init** to initialize the project as if you were using **NPM init** to initialize the NODEJS project。 > Before you develop a go project, you need to take some time to set up the GOPATH environment variable. --[official Guidance link] (https://golang.org/doc/install) DEP, like NPM, creates a Package.json-like file in a node. JS project to describe the project--GOPKG.TOML. Similar to Package-lock.json, there will also be a gopkg.lock file. Unlike the Nodejs project, where dependencies are placed in the Node modules folder, DEP relies on placing a folder called vendor. To add dependencies, you only need to run the DEP ensure-add github.com/pkg/errors command. At the end of the run, this dependency will appear in the Lock and toml files: "[[[constraint]] name =" Github.com/pkg/errors "Version =" 0.8.0 "' # # # Go handling asynchronous operations when using JAVASCR When IPT writes asynchronous code, we use some library or language features, such as:-Async Library-promises-or asynchronous functions with them, we can easily read from the file system: "' Javascriptconst fs = require (' FS ') Const ASYNC = require (' async ') const Filestoread = [' file1 ', ' File2 ']async.map (Filestoread, filePath) + = {FS . ReadFile (FilePath, ' Utf-8 ', Callback)}, (err, results) = {if (err) {return Console.log (ERR)}console.log (results)}) "And let's see how Go is implemented: ' ' Gopackage mainimport (" FMT "" Io/ioutil ") func main () {datFile1, ErrFile1: = Ioutil. ReadFile ("File1") if errFile1! = nil {panic (errFile1)}datfile2, ErrFile2: = Ioutil. ReadFile ("File2") if ErrFile2 ! = Nil {panic (errFile2)}fmt. Print (String (datFile1), String (datFile2)} "" Let's take a line to see how the above code works:-*import*--with the Import keyword, you can introduce project-dependent package files, just like node. js The *require*-func main--application in the portal-Ioutil. readfile--the function tries to read the file and consists of two return values:-DatFile1 If the read operation succeeds-errFile1 if there is an error in the read process-you can handle errors here, or directly let the program crash-FMT. Print is just the printout to the standard output above the example is OK, but the read file is read one after another. --Let's make a little improvement and get it asynchronous! Go has a concept called *goroutines* to handle multithreading. A *goroutine* is a lightweight thread that is managed by Go runtime. *goroutine* allows you to run the Go function concurrently. I end up using *errgroup* packages to manage or synchronize *goroutines*. This package provides a synchronization mechanism, error propagation, and a context cancellation mechanism for the same common task consisting of a set of *goroutines* subtasks. With *errgroup*, we can rewrite the code snippet of the read file and execute it concurrently: "Gopackage Mainimport (" context "" FMT "" Io/ioutil "" OS "golang.org/x/sync/ Errgroup ") Func Readfiles (CTX context. Context, files []string] ([]string, error) {g, ctx: = Errgroup. Withcontext (CTX) Results: = Make ([]string, Len (files)) for I, File: = Range Files {i, File: = i, Fileg. Go (func () error {data, err: = Ioutil. ReadFile (file) If Err = = Nil {Results[i] = string (data)}return err})}if err: = G.wait (); Err! = Nil {RETurn nil, Err}return results, Nil}func Main () {var files = []string{' file1 ', ' file2 ',}results, err: = Readfiles (context. Background (), files) if err! = Nil {fmt. Fprintln (OS. Stderr, Err) Return}for _, Result: = Range results {FMT. PRINTLN (Result)}} "# # using Go to build a REST API in node. JS, when it comes to choosing a framework to write HTTP services, we have a bunch of choices. Go is no exception in this regard. After Google, I chose *gin* to start. *gin* interface similar to *express* or *koa*, contains middleware support, JSON checksum and rendering: "' Gopackage mainimport" Github.com/gin-gonic/gin "Func Main () {// Create a default route with no middleware r: = Gin. The output of the New ()//default gin is standard output R. Use (gin. Logger ())//recovery middleware recovers from the exception and replies to 500r. Use (gin. Recovery ()) R.get ("/ping", func (c *gin). Context) {C.json, gin. h{"message": "Pong",})})//Monitor 0.0.0.0:8080r. Run (": 8080")} ' This is what I have now--no production experience. If this blog is helpful to you and you want to learn more about Go, contact me and I will continue to share my go learning journey. # # More Resources The above article mainly refer to the following link article:-https://peter.bourgon.org/go-best-practices-2016/-https://golang.github.io/dep-https:// blog.golang.org/defer-panic-and-recover-https://gobyexample.com-https://www.golang-book.com/
via:https://nemethgergely.com/learning-go-as-a-nodejs-developer/
Author: GERGELY Nemeth Translator: Chandler1142 proofreading: Rxcai
This article by GCTT original compilation, go language Chinese network honor launches
This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove
811 reads ∙1 likes