Go the Pythonista trip

background

Our main team back-end technology stack is Python, specific software engineering practice foregoing django / python there in detail. As usual do business mainly written by Python, do their own project is also Python tools, so in fact always wanted to try to experience the Go.

Free just last week, so the experience a bit of foundation set Go, Go write with a small service (micro-channel push messaging).

This article is Go Moe is a new road of Pythonista. There understanding fallacy, where improper operation, please enlighten up.

grammar

To use a language, habitually open  learn x in y minutes  to go over grammar.

Go so special is its keyword is very small, which makes Go's syntax is easy to write it down. Overall I think these grammar fun.

cycle

// can be written directly for death cycle 
for { 
    fmt.Println ( "the while to true ...")      
} 

// this keyword is very comfortable with the Range up 
the Data: = the Map [String] String { 
    "Key": "value" , 
} 
for Key, value: = {Data Range        
    fmt.Println ( "the while to true ...")      
}

enumerate

// keyword iota actually be made 
@ iota where both of the latter may be omitted 
const { 
    Unknown iota // = 0 
    for a Man = iota //. 1 
    for Woman iota = 2 // 
} 

// compartment 10 also meet the definition of enumeration preferences 
// `iota << 2` bit operations such definitions are possible 1/2/4/8 
const { 
    Unknown IOTA * 10 = 0 // 
    for a Man = 10 // 10 * IOTA 
    for Woman IOTA = 10 * / / 20 
}

Multi-judge expression

// if statement will take the last value of the expression, it is so judged common 
IF F, ERR: File.Open = (path); ERR = nil {! 
    Return the Response (400, err.Error ()) 
} 

/ / Analyzing this Boolean operation is common 
IF Data, OK: = json.Unmarshal (body); OK {! 
    return the Response (400, "invalid JSON body") 
}

goroutine

// go innate concurrency is also very elegant place 
FUNC sendTemplate () { 
    // This is time-consuming for a long time network requests 
} 

FUNC handleRequest (Context ctx) { 
    the validate () 
    // sendTemplate () 
    // ↑ If for speed, we you can not synchronize to send the template, then we use the keyword `go` will be a key asynchronous ↓ 
    Go sendTemplate () 
}

project

The syntax of the first chapter after too quickly to the second chapter: "How to play a project with the go"

Write the code, we must first look at the documents to turn out. So the first stop is the  official website golang.org

Go's official website is actually very friendly, from the most basic  to teach you how with the environment, wrote the initial project  , the  Effective Go  This comprehensive long texts are simple and obvious point.

Later installed to use the language environment, first with  GOPATH the environmental variables play a bit. But later found to Go comes after 1.12 go mod, simply look at this concept on the line. Then we first put it, to get started feeling Go directly to the tool bar chain.

Toolchain

Python installed after the main comes with a REPL with pip the package manager. Go installed later, will include a series of tools built fmt / test / vet / mod and so on.

  • go fmt
    • This is the first tool to get started Go biggest impression
    • It is an unsupported configuration code formatting tools, very strict
    • prefer tab over space
  • go test
    • Comes coverage, very good use
  • go vet
    • Seems comes linter

Play  go test , it was found that it is for  package to do the test, and Go inside,  package the concept is also very prominent. For example, when calling package method is to add the package name, so the best practice where there are "non-overlapping naming" rule. (For chestnuts, such methods should be called  xml.Parser instead  xml.XMLParser )

Write business

As we wrote an internal network provides an interface to RESTful style, then call micro-channel to send a message to inform the user of such a small service, in accordance with the inertia wanted to find Python  django +  wechatpy combination of business within a week to complete. Simple research in a circle, chose  gin +  gorm two large tools.

Go third-party libraries gave me the feeling is very straightforward. Because of the way that third-party libraries  go get -u github.com/gin-gonic/gin , direct pull is the latest code GitHub master branch, so the whole feeling of the community is based on distributed third-party consensus, we only have to comply with Community norms, it appears there will be no mining code ... (although there will be a center of mining codes)

Document, then read the research phase are actually GitHub README, GitHub is often visit the site, README style for each library are also markdown style is also very easy to read. Godoc few places to look real. Because the pull of the source code, so basically read the source code directly, much like the experience with Python.

Specific business code will skip the first, nothing special.

deploy

I began to prepare to deploy when there are a lot of fun topic. Go for example configuration of multi-environment.

Python (Django) of multi-environment I have been using environment variables + multiple configuration files, Go, then went to see what the community, the basic principle is similar. You can use environment variables, you can also use multiple configuration files (such as yaml), and the other is with the command parameters (flag library). Go actually more respected by the community flag, because it can be configured with the code (executable file) integration, more conducive to safeguarding. But I finally chose the environment variables + multiple configuration files ...

Compile the project, the deployment we use GitLab CI / Docker. Also ci-build / test / compile / docker-build / deploy five stage routine. Go there will be a lot more special is quoted official GitHub and Google Code, the pull speed is slower in the country, so in order to accelerate the build, own and we take the appropriate channels to enhance the accelerated speed. For now, the code from the trunk into the branches, to automatically send version probably took no more than 3min.

performance

Write your own small services go up, then we must first look at wrk measuring about QPS friends.

Python (Django) is actually the default synchronous mode, the foundation supports the QPS low, we use gevent + uwsgi coroutine model specially tuned through a simple interface to the server to obtain the current time, a small break in the machine 1CPU + 4G Memory of , Python (gevent) of QPS would be able to 1000, while the non-tuning Go (gin) QPS able to 10000. Good for you, ah, Go.

community

Go play in the week, in fact, I truly effective encoding time is not very long, most of the time wandering around in various community best practices document Go's.

In my eyes, removing a lot of shine Go language itself, the whole language community operator Go is also worth learning other languages. For example, the above mentioned official push the tool chain, which can effectively enhance the lower limit for all projects. Python last year has just had  a formatting tool Black  , own claim to be  at The uncompromising code Formatter  . (Python: Do not rush, studying at the school)

Feeling

Talk so much seemingly neutral, are feeling the actual speech, I'll focus sum up my feelings.

I am vegetables

Go write when I was able to feel that they are straightforward dishes. One is a lot of places I can sense the possibility of a simplified syntax, but my language skills have not reached an optimized bottle. For example,  Go 2 Draft in the check keywords  , I feel as if vaguely based  panic + recover can achieve a similar mechanism, but really want to write and write. And I feel completely Python written in Lisp.

The other one is to use the library, or "language ecology." Regardless of the standard library is usually used, or back-end business use of all kinds of tripartite library, or engineering used in unit testing, quality control of the library, I can only do field research when used.

In short because of a lack of basic knowledge, coupled with proficiency is not enough, Go write process there is always a kind of "I'm good food ah, do not understand this" wonderful feeling.

I like Go

Dish did not stop me from expressing love :)

Go who revealed the KISS principle very old-fashioned, it's even a lot of time to give me the feeling that even simple than Python. For example, best practices will tell you: "Do not prematurely split file, a problem can be resolved ten files directory does not require stratification."

Compared to Python, Go fast execution speed reveal one kind of unreasonable. Python-depth understanding concurrency model, after tuning CPU with the language parameter results, or an order of magnitude difference with Go ... (but on the development of the giant fast speed Python or ...)

Moreover, Go and the lovely  Gopher  ah ~

Go practice

Division I is the back end of the main Java technology stack with Python, I mainly written by Python.

In my short experience in terms of, Go will have a good performance on key high-performance service, but in the new business prototype multi-service, Web layer, Python magically speed of development is unparalleled ( akimbo)

The rear end of the current variety of popular basic framework is language-independent, we can choose the right technology stack according to different business application scenarios.

Enterprises in the choice of technology stack, in fact, will be more realistic to consider other factors, such as the difficulty of recruiting developers, code libraries, unified technology stack, a large team of decoupling management. In fact, these are also very in-depth, topic worth exploring.

Wrote a week Go, I am more convinced that their philosophy: "The engineer is to solve the problem of people, technology is a tool to solve the problem of not doing software engineering tools difficult to use say, is to He Yi: stab and kill people say, non I also, soldiers also? "

Follow-up

Week experience card a little too short, very something more to say.

There are follow-up time, Go on these topics, I will continue to study:

  • Service on the production line environment deployed position.
  • Go visualization services (monitoring, logging, tracking)
  • Using black magic to make the language more expressive foundation libraries
  • The interaction between the practice of cross-language service

Guess you like

Origin blog.csdn.net/java276582434/article/details/92107577