Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 25, 2023 09:04 pm GMT

Getting Started in Go

Purpose of this post is simply to present a little of why the language Go appeared and present a little of its syntax and demonstrate some areas where Go is more applied. For everyone who would like to further increase their arsenal for web development this post will help you to clarify some important points when we are starting and learning a new programming language.

Getting Started in Go

Before we start, it's important to point out that programming languages are tools and like any good tool, we have to know when to use them. There are scenarios and problems that are only solved with specific languages and there are other universes of problems that we have hundreds or thousands of languages that somehow solve the same problem. So like a good professional, the more tools you know to solve problems, the better it will be for your professional career .

The Go language in its universe of possibilities is a common use language I don't really like this term it seems like it's like a silver bullet and solves all problems but not really, Go was born by a purpose and solve problems of the web universe and take advantage of the new technology of multicores in servers, well this was the initial purpose .

History of the Go project

Robert Griesemer, Rob Pike, and Ken Thompson began sketching goals for a new language on the whiteboard on September 21, 2007. Within days, the goals settled into a plan to do something and a fair idea of what it would be like. . Design continued part-time in parallel with unrelated work. In January 2008, Ken started work on a compiler to explore ideas; it generated C code as its output. By mid-year, the language had become a full-time project and had established itself enough to try a production compiler. In May 2008, Ian Taylor started independently on a GCC frontend for Go using the preliminary specs. Russ Cox joined in late 2008 and helped move the language and libraries from prototype to reality.

Go became a public open source project on November 10, 2009 . Countless people from the community contributed ideas, discussions, and code.

There are now millions of Go programmers Gophers around the world, and there are more every day. The success of Go far exceeded expectations.

Why they created a new language

Go was born out of frustration with the existing languages and environments for the work we were doing at Google. Programming had become too difficult and the choice of languages was partly to blame. You had to choose between efficient compilation, efficient execution, or ease of programming; all three were not available in the same primary language. Programmers who might choose ease over security and efficiency, switching to dynamically typed languages like Python and JavaScript rather than C++ or, to a lesser extent, Java.

Go addressed these issues by trying to combine the programming ease of an interpreted, dynamic language with the efficiency and security of a statically compiled language. It was also intended to be modern, with support for networked and multicore computing. Finally, working with Go is intended to be fast: it should take a few seconds at most to build a large executable on a single computer.

A new Go language is born, to meet new needs and solve problems by taking advantage of the computational power as much as possible. And of course creating your mascot for the thousands of gophers that saw to emerge from this moment on.

Official site

To start in Go let's take a few steps back, let's start our whole trajectory knowing the official website of lang this is the official page golang.org, here we will find all the information we could know about Go and much more. Here we have the docs, packages, blog and our darling play.golang.org, language specs, download, Go tour and much more.

The official website apparently looks small but it is very complete and big. So we have practically everything we need to know about Go to start our learning in this language that is a phenomenon.

Where do I start on the Site

I'm going to create a line of reasoning so that we can understand Go in the most practical way possible.

Before installing Go, or running Go through play, let's go through some parts of the doc so that we can understand a little of the history of Go and why a new language was born in this universe of thousands of programming languages.

Effective Go

This link is the first one that everyone should read first.
Effective Go on this site you will find all the material you need to get a good idea of the Go language: Control Structure, Functions, Concurrent Programming using Goroutines, Methods, Maps and much more.

A go tour

This link would be the second most important link in my hierarchy for us to learn Go.
Tour Go on this site you will be able to test and take a look at some of the features of the Go language that's right all through the browser without having to install anything on the machine.

Playground Go

Here is very beautiful, you don't need to install anything on the machine to run something quickly in Go, just enter play.golang.org

Play Go on this site you will be able to run Go that's right we don't need to install anything for now, you can run everything through the browser and get to know the syntax of the language and learning.

Frequently Asked Questions

This link would be our third step, I believe you now have several questions, generated by Effective Go and by Tour that did.
Faq this is where you will take a few hours to read this, it doesn't have to be all at once, of course, but you must read it. This page is essential to organize your ideas and really understand a little more about Go .

This is one of the largest pages and requires more reading, but this page is essential for a better understanding of the Go language, the time you spend reading this page will surely save you hours of work.

Native Go packages

This link would be so you can take a look and understand how they are organized and how is the documentation of the functions, libs, pkgs that we can use in the Go language. This is one of the strengths of the language, it is very complete for web development for servers.
Pkg I chose pkg string here so you can check out how the documentation formatting is language and already with examples that can be executed by the browser, everything to facilitate learning and understanding .

Editors and IDE

This link is about the IDEs and Editors that you can use when you have Godando. The Go language doesn't need much for us to be able to edit our codes, but we have some interesting plugins to make our day to day even easier
Editors and IDE This link will not have Sublime and nvim which are two editors that I use around here on a daily basis, sublime by the survey survey, only 7.7% use sublime and vim 14% nvim is a plugin that they will use in vim. The darling and adopted by the Go team is VsCode with 41% adherence.

Strengths of the Go language

Before we do our famous Hello World let's show some strengths of the Language, let's preview the pillars and characteristics of the Go language.

3 Pillars

We have some well defined pillars in Go, this will help you to further clarify your horizon when it comes to Go.

  • Simplicity

  • Legibility

  • Productivity

This has become over the years something so standard for those who are developing in the Go universe that it sounds like poetry to the ears. We know that go is an attempt to join two different worlds, the world of compiled languages with interpreted languages, in 2007 the idea was born and with the objective of creating a new programming language.

Main features

In Go we have some outstanding features of the language that make it even more powerful for developing web applications for servers.

  • Only 25 keywords

  • Low learning curve

  • Compiled statically

  • Multiplatforms now support RISC-V

  • Concurrent Paradigm

  • Static Typing

  • Backward Compatibility

All these points make the language even more interesting, the team of engineers that developed the language did an excellent job or better see doing it, Go is simply fantastic some don't like its designer but it's understandable more than 20 years developing in OO and Functional paradigms as if there is no life on another planet is understandable .

Installing Go

This is the moment we've all been waiting for, get your hands dirty and install locally, on the official website you can't go wrong, there's nothing simpler than installing Go on your machine so you can program in Go. Taking advantage of this and making it clear that: We don't need to install Go on the server, this is exactly what you read, on your server whatever it may be, On-premises, an Ec2 from Aws or a pod on k8s whether it's on Gke, or k8s from DigitalOcean, that is on ECS or EKS, whether it is a serverless or on any hosting server of your choice, what you will need is the binary whether in a docker image for example or not. This is one of the strengths of Go, we don't need to carry stuff to the server this is one of the great benefits of using Go in web applications on servers and this is what Go became known for like the containers language.

Knowing all this, let's go to install Go and see how complex it is , just kidding

Install Go in this link you will have the step by step on how to install in different Operating Systems but I will leave the installation in Linux here.

Installation on Linux

If you have a previous version of Go installed, be sure to remove it before installing another one.

  1. $ sudo rm -rf /usr/local/go

  2. Download the file by clicking here go1.15.6 and extract it in /usr/local

  3. $ sudo tar -C /usr/local -xzf go1.15.6.linux-amd64.tar.gz

  4. Add /usr/local/go/bin to the PATH environment variable.

  5. $ export PATH=$PATH:/usr/local/go/bin

  6. To make what we did above global, that is, every time you enter your terminal go is executed, you can do this by adding the following line that I showed above to your $HOME/.profile or /etc/profile (for a system-wide install) or your bash or whatever you're using in your Linux environment.

  7. Note: Changes made to a profile file may not apply until the next time you log in to your computer. To apply the changes immediately, just run the shell commands directly or run them from the profile using a command like source $HOME/.profile.

  8. Verify that you have installed Go by opening a command prompt and typing the following command:

go version

If all goes well you will see: *go version go1.15.6 linux/amd64
*beautiful, simply beautiful you can say, very simple.

Hello World

Now it's time for our first "hello world" using Go.

There's no secret, we can use any editor we saw above and go to the top. In Go we don't need to compile when we're having, we can simply run our programs without having to turn them into binaries, ie compile.

go run main.go

Below is our first hello world, and just save the file with the .go extension and put the name _main.go_ then just run it with the command go run main.go, in our example I called file from main.go

package mainfunc main() {  println("My first Hello World")}
package mainimport(    "fmt")func main() {  fmt.Println("My first Hello World")}
$ go run main.go

This hello world of ours is the smallest structure we can assemble to output to the terminal.

To be a little clearer when using the println function we have to know that it is a built-in function (at runtime) that can eventually be removed, while the fmt package is in the standard library, which will persist.

go build

Now let's turn it into a binary let's compile it and for that we will use go build or GOARCH=386 GOOS=linux go build -o myprogram main.go we are now informing the architecture and operating system that we want to compile our Go program.

$ GOARCH=386 GOOS=linux go build -o myhello main.go

This command will make the build it will generate an executable a binary to run on your operating system. Very easy isn't it? I would say very beautiful. With this binary you'll be able to run it on your machine or on any server that has the same architecture and operating system that you made for your compilation.

It's important to always emphasize this detail: We don't install anything Go on our web servers is exactly what you read, you don't need to install anything, you just need the binary. This is why Go became known as the Language of Containers. Are you saying this isn't fantastic? To run a web application on your server, just send the binary to it. Wow, that's right just from the binary without needing to take anything else related to your project at all.

Go and Docker

Since we are talking about docker and saying that we only need the binary to run our project on Go let's present what our image would look like using docker so that we can now use Go on servers like Google's GKE, AWS's EKS, or k8s from DigitalOcean or simply use with docker.

################################################### Dockerfile distroless##################################################FROM golang:1.15 as builderWORKDIR /go/src/mainCOPY . .RUN CGO_ENABLED=0 GOOS=linux go build -o main main.goRUN cp main /go/bin/main############################## STEP 2 build a small image#############################FROM gcr.io/distroless/baseCOPY --from=builder /go/bin/main /CMD["/main"]

Look how beautiful just under 10 lines. We have a Go image so we can compile our project and then we do something like Scratch but we are using distroless which is a very small lean base and contains our binary. I'm sorry, but isn't this fantastic or simply beautiful?

The distroless concept is simple, it assumes that we focus on our application and less on the Linux distribution.

Now let's make a small example of a rEST API just to exemplify our Dockerfile and show in practice how simple it is to upload a docker image of our project.

package mainimport("log""net/http")func main() {mux := http.NewServeMux()mux.HandleFunc("/api/v1/ping", Ping)log.Println("Run Server 8080")log.Fatal(http.ListenAndServe(":8080", mux))}func Ping(w http.ResponseWriter, r *http.Request) {log.Println("server ok")w.WriteHeader(http.StatusOK)w.Write([]byte(`{"msg":"pong"}`))}

Now we just build our project with the following command:

$ docker build no-cache -f Dockerfile -t jeffotoni/apisimplego:latest .

this will generate an image locally on your machine and now just run it for us to test.

$ docker run rm name apisimplego -p 8080:8080 jeffotoni/apisimplego

Ready now, just shoot to our /api/v1/ping endpoint that we created

$ curl -i localhost:8080/api/v1/ping

Say it's not beautiful

Conclusion

This post is a simple summary for you who would like to increase your web programming arsenal. I hope you enjoyed.

The channel where the live took place: https://youtube.com/user/jeffotoni

The PDF link of the presentation can be found at: speakerdeck.com/jeffotoni


Original Link: https://dev.to/jeffotoni/getting-started-in-go-599d

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To