fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,30 @@
---
title: A simple web server in Go
---
The Go programming language is well-known for having a built-in web server. In this article you will learn how you can easily make your own web server with Go. You won't need any other packages beside the ones that are already built in!
First, hop in to your text editor. Then create a file called `webserver.go` and enter the following code:
```go
package main
import (
"net/http"
"io"
)
func main() {
http.HandleFunc("/", servePage)
http.ListenAndServe(":8080", nil)
}
func servePage(writer http.ResponseWriter, reqest *http.Request) {
io.WriteString(writer, "Hello world!")
}
```
Let's break down the block of code above. We import the `net/http` package: this package contains the web server itself. Then we also import the `io` package, we will make use of this later to actually serve something to the client.
In the `main` function we do two things. First of all we instruct the server to let the function called `servePage` handle all incoming traffic to `/` - in this case it means that it handles requests to *any* `URL`. The second thing we do is actually activating the server. We do this using a function named `ListenAndServe`. This function requires two parameters: the `port` (as `string`), in this case it's `8080`, and the `handler` (as `Handler`) - however the last one isn't important yet. We will just make it `nil` and everything will work just fine.
In the `servePage` we do just one simple thing, for now. Using the `io` package and the `WriteString` function that it contains we can respond to the clients' request with the text `Hello world!` (or any other string, of course). You also might have noticed that the `servePage` function has two arguments: the `writer` and the `request`. With the writer you can actually respond to a `HTTP` request and with the `request` you may get more information about the request itself.
Congratulations! You just created your first web server! If you want to test it: just run `go run webserver.go`, fire up a browser and navigate to `http://localhost:8080`!

View File

@ -0,0 +1,13 @@
---
title: Documentation
---
# Official documentation
1. [Language specification](https://golang.org/ref/spec)
2. [Effective Go](https://golang.org/doc/effective_go.html)
## Godoc.org (https://godoc.org/)
The documentation within golang.org includes the standard library and the src.
The good thing about __godoc.org__ is that includes the standard library AND third-party packages.

View File

@ -0,0 +1,89 @@
---
title: Go Functions
---
## Go Functions
A function takes zero or more parameters of any type, does some logic with them and may return one or more values.
Golang's function syntax is:
```go
func sum(parameter1 int64, parameter2 int64) int64 {
return parameter1+parameter2
}
```
Here, the name of the function is `add`. It takes to parameters, `parameter1` and `parameter2` of type `int64`
and returns another int64, the sum of the two parameters.
### Return
After a `return` is reached, the function exits without executing more code.
```go
func sum(parameter1 int64, parameter2 int64) int64 {
return parameter1+parameter2
// Unreachable code
fmt.Printf("Don't print me")
}
```
### Calling a function
The above function would be called like this:
```go
sum(4, 5)
```
The value of this expression is 9.
### Omit parameter type
If two or more consecutive parameters are the same type, it may be stated only once.
```go
function foo(x, y, z int64, name string) {
fmt.Printf("%d %d %d %s", x, y, z, name)
}
```
Here `x`, `y`, and `z` are type `int64`, and `name` is a string.
### Returning multiple values
A function can return zero or more values.
To return nothing, omit the return type:
```go
function helloWorld() {
fmt.Printf("Hello world!")
}
```
To return one value specify its type:
```go
function getHelloWorld() string {
return "Hello world!"
}
```
To return more than one value specify their types, wrapped in `()` and separated by commas:
```go
function getHelloWorldAndBestLanguage() (string, string) {
return "Hello world!", "Golang"
}
```
To receive these values, simply declare variables separated by commas like this:
```go
helloWorld, bestLanguage := getHelloWorldAndBestLanguage()
// helloWorld == "Hello world!"
// bestLanguage == "Golang"
```
### Naked returns
You can name the return types so that you don't need to pass variable to the return statement:
```go
func duplicate(s string) (first, second string) {
first = s
last = s
return
}
func main() {
fmt.Println(split("Hello world!")) // ("Hello world!", "Hello world!")
}
```
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
https://tour.golang.org/basics/4

View File

@ -0,0 +1,17 @@
---
title: Go Channels
---
## Go Channels
This is a stub. [Help our community expand it](https://github.com/freecodecamp/guides/tree/master/src/pages/go/go-channels/index.md).
[This quick style guide will help ensure your pull request gets accepted](https://github.com/freecodecamp/guides/blob/master/README.md).
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
* [A Tour of Go](https://tour.golang.org/concurrency/2)
* [Go By Example](https://gobyexample.com/channels)
* [Golang Book](https://www.golang-book.com/books/intro/10)
* [The Go Programming Language Specification](https://golang.org/ref/spec#Making_slices_maps_and_channels)

View File

@ -0,0 +1,44 @@
---
title: Go Functions
---
## Go Functions
A function is a block of code that performs a task when it's called, such that the function's name identifies it and is used in calling the function.
A function's declaration starts with the keyword `func` followed by the function's name then the arguments of the function and finally the returned values types. The declaration binds the function name to the function. Keep in mind that the type comes after the variable name in both the arguments and the returned values. An example of a function's declaration is the following
```go
func add(a int, b int) int
```
A function can have 0 or many arguments depending on its desired functionality
```go
func zero() int { /* Function Definition */ }
func increment(x int) int { /* Function Definition */ }
func add(x, y int) int { /* Function Definition */ }
```
Go supports returning multiple values. The function below returns 2 values: the sum of the 2 arguments, and the difference between the first and the second argument
```go
func addAndSubtract(x, y int) (int, int) {
return x + y, x - y
}
addAndSubtract(7, 4) // Returns 11, 3
```
Go also supports naming the returned values
```go
func mulitplyByThreeAndDivideByFive(x int) (product int, quotient int) {
product = x * 3
quotient = x / 5
return
}
mulitplyByThreeAndDivideByFive(20) // Returns 60, 4
```
#### More Information:
* [A Tour of Go](https://tour.golang.org/basics/4)
* [Go By Example](https://gobyexample.com/functions)
* [Golang Book](https://www.golang-book.com/books/intro/7)
* [The Go Programming Language Specification](https://golang.org/ref/spec#Function_declarations)

View File

@ -0,0 +1,65 @@
---
title: Go Maps
---
## Go Maps
A map, called a _dictionary_ in other languages, "maps" keys to values.
A map is declared like this:
```go
var m map[Key]Value
```
This map has no keys and no keys can be added to it.
To create a map, use the `make` function:
```go
m = make(map[Key]Value)
```
Anything can be used as a key or as a value.
### Modifying maps
Here are some common action with maps.
#### Inserting/Changing elements
Create or change element `foo` in map `m`:
```go
m["foo"] = bar
```
#### Getting elements
Get element with key `foo` in map `m`:
```go
element = m["foo"]
```
#### Deleting elements
Delete element with key `foo` in map `m`:
```go
delete(m, "foo")
```
#### Check if a key has been used
Check if key `foo` has been used in map `m`:
```go
element, ok = m["foo"]
```
If `ok` is `true`, the key has been used and `element` holds the value at `m["foo"]`.
If `ok` is `false`, the key has not been used and `element` holds its zero-values.
### Map literals
You can directly create map literals:
```go
var m = map[string]bool{
"Go": true,
"JavaScript":false,
}
m["Go"] // true
m["JavaScript"] = true // Set Javascript to true
delete(m, "JavaScript") // Delete "JavaScript" key and value
language, ok = m["C++"] // ok is false, language is bool's zero-value (false)
```
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
* [A Tour of Go](https://tour.golang.org/moretypes/19)
* [Go By Example](https://gobyexample.com/maps)
* [Golang Book](https://www.golang-book.com/books/intro/6#section3)
* [The Go Programming Language Specification](https://golang.org/ref/spec#Making_slices_maps_and_channels)

View File

@ -0,0 +1,27 @@
---
title: Go Playground
---
# The Golang Playground
The Golang playground is a website where you can write Go code online, so that you don't have to set up any developmet environment.
Just open a new browser window clicking [Playground](https://play.golang.org).
Once there you'll get the buttons:
1. Run
2. Format
3. Imports
4. Share
The Run button sends the instruction to compile the code you wrote to the google servers that run the golang backend.
The Format button implements the idiomatic formatting style of the language, you can read more [here](https://golang.org/pkg/fmt/)
Imports just check what packages you have declared within import(). An import path is a string that uniquely identifies a package. A package's import path corresponds to its location inside a workspace or in a remote repository (explained below). [More](https://golang.org/doc/code.html#ImportPaths)
With Share you get an URL where the code you just wrote is saved. Useful when asking for help showing your code.
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
* [The Go Playground](https://play.golang.org/)
* [A Tour of Go](https://tour.golang.org/welcome/4)

View File

@ -0,0 +1,39 @@
---
title: Go Pointers
---
## Go Pointers
This is a stub. [Help our community expand it](https://github.com/freecodecamp/guides/tree/master/src/pages/go/go-pointers/index.md).
[This quick style guide will help ensure your pull request gets accepted](https://github.com/freecodecamp/guides/blob/master/README.md).
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Pointers
Go has pointers. A pointer holds the memory address of a value.
The type *T is a pointer to a T value. Its zero value is nil.
var p *int
The & operator generates a pointer to its operand.
i := 42
p = &i
The * operator denotes the pointer's underlying value.
fmt.Println(*p) // read i through the pointer p
*p = 21 // set i through the pointer p
This is known as "dereferencing" or "indirecting".
Unlike C, Go has no pointer arithmetic.
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
* [A Tour of Go](https://tour.golang.org/moretypes/1)
* [Go By Example](https://gobyexample.com/pointers)
* [Golang Book](https://www.golang-book.com/books/intro/8)
* [The Go Programming Language Specification](https://golang.org/ref/spec#Address_operators)

View File

@ -0,0 +1,17 @@
---
title: Go Slices
---
## Go Slices
This is a stub. [Help our community expand it](https://github.com/freecodecamp/guides/tree/master/src/pages/go/go-slices/index.md).
[This quick style guide will help ensure your pull request gets accepted](https://github.com/freecodecamp/guides/blob/master/README.md).
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
* [A Tour of Go](https://tour.golang.org/moretypes/7)
* [Go By Example](https://gobyexample.com/slices)
* [Golang Book](https://www.golang-book.com/books/intro/6#section2)
* [The Go Programming Language Specification](https://golang.org/ref/spec#Making_slices_maps_and_channels)

View File

@ -0,0 +1,137 @@
---
title: Go Structs
---
## Go Structs
In Go, structs are used to store data and related functions. An example might be a struct to represent a User:
```go
type User struct {
FirstName string
LastName string
Email string
Age int
}
```
Here we can store a user's first name, last name, email address, and age. The name of the property is followed by the type of data we want to store. For example, the `FirstName` property is a `string` whereas the `Age` property is an `int`.
### Creating objects
To initialise a new object, we can use the Go shorthand syntax for creating and assigning variables. We can either pass the data in at this point or set the data at a later time:
```go
func main() {
type MyInt int64
// Create a user and set both the first and last name properties
user1 := User{
FirstName: "John",
LastName: "Wick",
}
// Now we have our user object, we can set the data like this
user1.Email = "john@wick.com"
user1.Age = 30
}
```
### Object methods
Go enables declaring methods to struct types and non struct types. This enables grouping of relevant operations to the data it affects. In this example we will write a method on the `User` struct to generate the full name of the user and String method on `MyInt` type to return a String:
```go
func (myint MyInt) String() string {
return fmt.Sprintf("%d", myint)
}
func (u User) FullName() string {
return strings.Join([]string{u.FirstName, u.LastName}, " ")
}
```
This method will join the first and last name of the user with a space in between. Calling the method might look like this:
```go
fmt.println(user1.FullName())
```
### Struct Tags
Struct tags are used to modify how encoders handle the data. For example, setting the key names when encoding to JSON:
```go
type User struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
Age int `json:"age"`
}
```
### Exported Data
Structs can contain both exported (public) and unexported (private) properties. This is set by either having an uppercase first letter for exported or a lowercase first letter for unexported. In this example, we will make the email property private:
```go
type User struct {
// Exported Data
FirstName string
LastName string
Age int
// Unexported Data
email string
}
```
Doing this will make the following code throw a compilation error as it is trying to assign value to an unexported property:
```go
user1.email = "john@wick.com"
```
Same principle applies when attempting to read data from an unexported property.
This also applies to methods:
```go
// Exported method. This can be called from anywhere
func (u User) Email() {
return u.email
}
// Unexported method. This can only be called by other methods on this struct
func (u User) updateLoginCount {
// code to update login count...
}
```
### Modifying properties via methods
To modify the data of an object from within one of it's methods, the object must be a pointer. An example might look like this:
```go
// SetEmail sets the user's email address
func (u *User) SetEmail(email string) {
u.email = email
}
// Email accessor
func (u *User) Email() string {
return u.email
}
func main() {
// Creating the user1 pointer
user1 = &User{
FirstName: "John",
LastName: "Wick",
}
// Set the user's email address
user1.SetEmail("john@wick.com")
// Access and print the user's email address
fmt.println(user1.Email())
}

View File

@ -0,0 +1,33 @@
---
title: Go Variables
---
# Variable declarations in Go
## Method 1: Regular Variable Declarations
A regular variable declaration creates one or more variables by binding identifiers with a type and an initial value. If a variable is declared without a type, then that variable is given the type of the corresponding initialization value in the assignment. If a variable is defined with no initial value, then the variable is initialized to its [zero value](https://golang.org/ref/spec#The_zero_value).
The following examples are all valid variable declarations in go:
``` go
var x int = 1
var y int
var z = 0
var a, b float32 = -1, -2
```
## Method 2: Short Variable Declarations
Shorthand variable declarations create variables with only an identifier and an initial value. The `var` keyword and types are not needed to declare a variable using shorthand syntax:
``` go
x := 1
text, err := ioutil.ReadAll(reader)
```
Short variable declarations may appear only inside functions. In some contexts such as the initializers for `if`, `for`, or `switch` statements, they can be used to declare local temporary variables.
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
* [A Tour of Go](https://tour.golang.org/basics/8)
* [Go By Example](https://gobyexample.com/variables)
* [Golang Book](https://www.golang-book.com/books/intro/4)
* [The Go Programming Language Specification](https://golang.org/ref/spec#Variable_declarations)

View File

@ -0,0 +1,20 @@
---
title: Goroutines
---
## Goroutines
This is a stub. [Help our community expand it](https://github.com/freecodecamp/guides/tree/master/src/pages/go/goroutines/index.md).
[This quick style guide will help ensure your pull request gets accepted](https://github.com/freecodecamp/guides/blob/master/README.md).
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Goroutines are functions or methods that run concurrently with other functions or methods. Goroutines can be thought of as light weight threads. The cost of creating a Goroutine is tiny when compared to a thread.
Prefix the function or method call with the keyword `go` and you will have a new Goroutine running concurrently.
#### More Information:
* [A Tour of Go](https://tour.golang.org/concurrency/1)
* [Go By Example](https://gobyexample.com/goroutines)
* [Golang Book](https://www.golang-book.com/books/intro/10)
* [The Go Programming Language Specification](https://golang.org/ref/spec#Go_statements)

View File

@ -0,0 +1,65 @@
---
title: Hello World in Go
---
To install Go in your computer, download its installer from <a href='https://golang.org/dl/' target='_blank' rel='nofollow'>here</a> and install it by following these <a href='https://golang.org/doc/install' target='_blank' rel='nofollow'>installation instructions</a>.
## First Go program
Create a file named `main.go` and add the following code in it :-
```go
package main // Package declaration
import "fmt" // Importing packages
// Function declaration
func main() {
fmt.Println("Hello, World!")
}
```
Now, run the above program from Terminal/Command Line. To do this, open Terminal/Command Line and move to the directory in which `main.go` is present. First compile the program and run `go build main.go`. Then run the command `go run main.go` to run program.
You should see the ouptut similar to the following output :-
$ go build main.go
$ go run main.go
Hello, World!
## Analysis
### Package declaration
```go
package main
```
In go, every program is associated with a “package”, or a collection of associated programs. A notable exception is the special package “main”, which indicates to the go complier that it should run the following program.
### Imports
```
import “fmt”
```
If you want to use functions from other packages, you need to import them. There are certain packages developed by the go maintainers (called the “standard library”) and can be found at https://golang.org/pkg/. In this case, we need the “fmt” package for our print statement (below).
### Function declaration
```go
func main() {
}
```
Functions are the heart of any program in go. They can have arguments and return values, but the `main` function does neither of these. It acts as the “entry point,” or where go looks first to run your program. We want our Hello World program to print, so we want to put our code here.
### Print statement
```go
fmt.Println("Hello, world!")
```
Go doesnt require semicolons at the end of lines, as the complier adds them automatically. The package `fmt` (which we imported above!) has function `Println`, which we invoke using the `.` syntax. We pass arguments to the function between the parens. In this case, the argument is the string we want to print (`"Hello, world!"`). Note that the string itself is enclosed in quotation marks.
Now that you have the tools necessary, go out and make your own Go programs! The best way to learn is to experiment. If you ever need help, try the excellent go documentation: https://golang.org/doc/

View File

@ -0,0 +1,43 @@
---
title: if else Statements
---
## Introduction
The `if` statement executes a statement if a specified condition is **true**. If the condition is **false**, another statement can be executed using the `else` statement..
**Note:** The `else` statement is optional.
```Go
x := 7
if x%2 == 0 {
// This statement is executed if x is even
} else {
// This statement is executed if x is odd
}
```
Multiple `if...else` statements can be nested to create an `else if` clause.
```go
x := 7
if x == 2 {
// this statement is executed if x is 2
} else if x == 4 {
// this statement is executed if x is 4
} else if x == 7 {
// this statement is executed if x is 7
} else {
// this statement is executed if none of the aboves is true
}
```
In Go you can precede an `if` condition with a statement. The containing variable definition is then valid for the complete `if` block.
```go
if x := 3; x == 2 {
// this statement is executed if x is 2
} else if x == 3 {
// this statement is executed if x is 3
} else {
// this statement is executed if none of the aboves is true
}
```

View File

@ -0,0 +1,67 @@
---
title: If in Go
---
# If in Go
Go's `if` statements are like its `for` loops; the expression need not be surrounded by parentheses
`(` `)` but the braces `{` `}` are required.
```go
func sqrt(x float64) string {
if x < 0 {
return sqrt(-x) + "i"
}
return fmt.Sprint(math.Sqrt(x))
}
```
Like `for`, the `if` statement can start with a short statement to execute before the condition.
Variables declared by the statement are only in scope until the end of the `if`.
```go
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
}
return lim
}
```
## If and else
Variables declared inside an `if` short statement are also available inside any of the `else` blocks.
```go
package main
import (
"fmt"
"math"
)
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
} else {
fmt.Printf("%g >= %g\n", v, lim)
}
// can't use v here, though
return lim
}
func main() {
fmt.Println(
pow(3, 2, 10),
pow(3, 3, 20),
)
}
```
Running the above program produces an output similar to the following output -
```
$ go run if.go
27 >= 20
9 20
```

84
guide/english/go/index.md Normal file
View File

@ -0,0 +1,84 @@
---
title: Go
---
## Go
![Go bumper](https://golang.org/doc/gopher/bumper320x180.png)
**Go** (or **golang**) is a programming language created at Google in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is a compiled, statically-typed language in the tradition of Algol and C. It has garbage collection, limited structural typing, memory safety, and CSP-style concurrent programming features added. The compiler and other language tools originally developed by Google are all free and open source. Its popularity is increasing fast. It is a great choice for building web applications.
For more information head to [Go's Homepage](https://golang.org/)
Want a quick [Tour of Go?](https://tour.golang.org/welcome/1)
## Pre-Installations:
-----------
#### Install Golang with Homebrew:
```bash
$ brew update
$ brew install golang
```
#### When installed, try to run go version to see the installed version of Go.
### Setup the workspace:
------
##### Add Environment variables:
First, you'll need to tell Go the location of your workspace.
We'll add some environment variables into shell config. One of does files located at your home directory bash_profile, bashrc or .zshrc (for Oh My Zsh Army)
```bash
$ vi .bashrc
````
then add those lines to export the required variables
#### This is actually your .bashrc file
```bash
export GOPATH=$HOME/go-workspace # don't forget to change your path correctly!
export GOROOT=/usr/local/opt/go/libexec
export PATH=$PATH:$GOPATH/bin
export PATH=$PATH:$GOROOT/bin
```
#### Create your workspace:
--------
##### Create the workspace directories tree:
```bash
$ mkdir -p $GOPATH $GOPATH/src $GOPATH/pkg $GOPATH/bin
$GOPATH/src : Where your Go projects / programs are located
$GOPATH/pkg : contains every package objects
$GOPATH/bin : The compiled binaries home
```
### Quickstart
For a quickstart and boilerplate Go project, try <a href='https://www.growthmetrics.io/open-source/alloy' target='_blank' rel='nofollow'>Alloy</a>
1. Clone Alloy repository
```
git clone https://github.com/olliecoleman/alloy
cd alloy
```
2. Install the dependencies
```
glide install
npm install
```
3. Start the development server
```
go install
alloy dev
```
4. Visit website at `http://localhost:1212`
*Alloy uses Node, NPM, and Webpack*
### Go Playground
[Go Playground](https://play.golang.org/)
Learning how to install go on your local machine is important, but if want to start playing with go right in your browser, then Go Playground is the perfect sandbox to get started right away! To learn more about the Go Playground see their article titled [Inside the Go Playground](https://blog.golang.org/playground)

View File

@ -0,0 +1,22 @@
---
title: Installing Go in Arch Linux using pacman
---
### Installing Go in Arch Linux using pacman
Using Arch Linux Package Manager (pacman) is the easiest way to install Go. Based on the Arch Linux philosophy of providing new software versions very fast, you will get a very current version of go.
Before you can install the go package, you have to bring the system up to date.
```sh
$ sudo pacman -Syu
$ sudo pacman -S go
```
#### Check installation and version of go
To check if go was successfully installed, use:
```sh
$ go version
> go version go2.11.1 linux/amd64
```
This will print to the console the version of go, while at the same time making sure the installation went smoothly.

View File

@ -0,0 +1,24 @@
---
title: Installing Go
---
# Installing Go
## Installing Go in Ubuntu
* [Installing Go using apt-get](https://guide.freecodecamp.org/go/installing-go/ubuntu-apt-get). This is the easiest method for installing go in ubuntu.
* [Installing Go using tarball](https://guide.freecodecamp.org/go/installing-go/ubuntu-tarball). Use this method if you wish to install the latest stable version of go.
## Installing Go in Mac OS X
* [Installing Go using Package Installer](https://guide.freecodecamp.org/go/installing-go/mac-package-installer). Easiest method to install latest stable version of go.
* [Installing Go using tarball](https://guide.freecodecamp.org/go/installing-go/mac-tarball). For those that wish to use the terminal.
## Installing Go in Windows
* [Installing Go using the MSI Installer](https://guide.freecodecamp.org/go/installing-go/windows-installer)
## Installing Go from source
* To install Go from source reffer to the <a href="https://golang.org/doc/install/source" rel="nofollow" target="_blank">installing from source documentation<a/>
Reference: <a href="https://golang.org/doc/install#install" rel="nofollow" target="_blank">golang install documentation</a>

View File

@ -0,0 +1,17 @@
---
title: Installing Go in Mac OS X using Package Installer
---
### Installing Go in Mac OS X using Package Installer
From the [golang's download page](https://golang.org/dl/), get the Mac package installer (ending in .pkg) and run it.
![screenshot of golang's download page as of this writting, highliting link](https://raw.githubusercontent.com/AlexandroPerez/resources/master/img/mac_package_installer.jpg "Mac package installer link")
#### Check installation and version of go
To check if go was successfully installed, open your terminal and use:
```sh
$ go version
```
This should print to the console the version of go, while at the same time making sure the installation went smoothly.

View File

@ -0,0 +1,31 @@
---
title: Installing Go in Mac OS X using a tarball
---
### Installing Go in Mac OS X using a tarball
#### Link to tarball
You can get the link to the Mac OS tarball archive from the Latest Stable section of the [golang download page](https://golang.org/dl/).
![screenshot of golang's download page as of this writting, highliting link](https://raw.githubusercontent.com/AlexandroPerez/resources/master/img/mac_tarball.jpg "Mac tarball link")
#### Installation Process
> In this installation process we'll use the latest stable version as of this writing (go 1.9.1). For a newer or older version simply replace the link in the first step. Check the [golang download page](https://golang.org/dl/) to see what versions are currently available.
##### Installing Go 1.9.1
```
$ curl -O https://storage.googleapis.com/golang/go1.9.1.darwin-amd64.tar.gz
$ sudo tar -C /usr/local -xzf go1.9.1.darwin-amd64.tar.gz
$ export PATH=$PATH:/usr/local/go/bin
```
#### Check installation and version of go
To check if go was successfully installed, use:
```sh
$ go version
```
This should print to the console the version of go, while at the same time making sure the installation went smoothly.

View File

@ -0,0 +1,23 @@
---
title: Installing Go in Ubuntu using apt-get
---
### Installing Go in Ubuntu using apt-get
Using Ubuntu's Source Package Manager (apt-get) is the easiest way to install Go. You won't get the latest stable version, but for the purpose of learning this should be enough.
>As of this writing, Ubuntu Xenial's version of go is 1.6.1, while the latest
stable version is 1.9.1
```sh
$ sudo apt-get update
$ sudo apt-get install golang-go
```
#### Check installation and version of go
To check if go was successfully installed, use:
```sh
$ go version
> go version go1.9.1 linux/amd64
```
This will print to the console the version of go, while at the same time making sure the installation went smoothly.

View File

@ -0,0 +1,59 @@
---
title: Installing Go in Ubuntu using a tarball
---
### Installing Go in Ubuntu using a tarball
>This is the recommended way to install go if you wish to get the latest stable version available from the golang website.
#### Check your system Architecture
Before proceeding make sure you know if your system is 32 or 64 bit. If you don't know, run the following command to find out:
```sh
$ lscpu | grep Architecture
```
If you see ``` Architecture: x86_64``` your system is 64bit, otherwise if you get ```Architecture: i686```, then your system is 32bit. Now that you know your system architecture, let's proceed.
#### Picking the right tarball
From the [golang download page](https://golang.org/dl/), you'll need to get the link to the right tarball file (.tar.gz) for your system.
If your system is 64bit, copy the link to the .tar.gz file for Linux systems with x86_64 architecture. For example, the latest stable version for 64bit systems as of this writing is ```go1.9.1.linux-amd64.tar.gz```
![screenshot of golang's download page as of this writting, highliting link](https://raw.githubusercontent.com/AlexandroPerez/resources/master/img/ubuntux64.jpg "x64 tarball link")
If your system is 32bit, copy the link to the .tar.gz file for Linux systems with x86 architecture. As of this writing the latest file is ```go1.9.1.linux-386.tar.gz```
![screenshot of golang's download page as of this writting, highliting link](https://raw.githubusercontent.com/AlexandroPerez/resources/master/img/ubuntux86.jpg "x86 tarball link")
After copying the link, simply replace the link in the Installation process found below with the link you got from the download page.
#### Installation Process
> In this installation process we'll use the links to the go 1.9.1 tarballs as an example. For a newer or older version simply replace the link in the first step. Check the [golang download page](https://golang.org/dl/) to see what versions are currently available.
##### Go 1.9.1 for 64bit systems:
```
$ wget https://storage.googleapis.com/golang/go1.9.1.linux-amd64.tar.gz
$ sudo tar -C /usr/local -xzf go1.9.1.linux-amd64.tar.gz
$ export PATH=$PATH:/usr/local/go/bin
```
##### Go 1.9.1 for 32bit systems:
```
$ wget https://storage.googleapis.com/golang/go1.9.1.linux-386.tar.gz
$ sudo tar -C /usr/local -xzf go1.9.1.linux-386.tar.gz
$ export PATH=$PATH:/usr/local/go/bin
```
#### Check installation and version of go
To check if go was successfully installed, use:
```sh
$ go version
> go version go1.9.1 linux/amd64
```
This will print to the console the version of go, while at the same time making sure the installation went smoothly.

View File

@ -0,0 +1,22 @@
---
title: Installing Go in Windows using the MSI Installer
---
### Installing Go in Windows using the MSI Installer
From the [golang's download page](https://golang.org/dl/), get the Windows MSI installer and run it. You'll have to pick between the 64bit and 32bit versions. If you don't know what architecture your Windows version is running, just do a quick Google search to find out.
>Most current versions of Windows are 64bit, so you should be ok getting the 64bit version in the featured downloads section, but if your computer is quite old, the 32bit version should be the safest bet.
##### 64-bit Windodows Installer
![screenshot of golang's download page as of this writting, highliting link](https://raw.githubusercontent.com/AlexandroPerez/resources/master/img/win_installerx64.jpg "x64 Windows msi installer link")
##### 32-bit Windodows Installer
![screenshot of golang's download page as of this writting, highliting link](https://raw.githubusercontent.com/AlexandroPerez/resources/master/img/win_installerx86.jpg "x86 Windows msi installer link")
#### Check installation and version of go
To check if go was successfully installed, open your command prompt and use:
```
> go version
```
This should print to the console the version of go, while at the same time making sure the installation went smoothly.

View File

@ -0,0 +1,74 @@
---
title: Loops
---
# For loop in Go
Go has only `for` loop. The basic `for` loop has three components separated by `;` -
* the **init** statement: executed before the first iteration
* the **condition** expression: evaluated before every iteration
* the **post** statement: executed at the end of every iteration
The **init** statement is often a short variable declaration. The variables declared there are visible only in the scope of the `for` statement. The loop stops iterating once the boolean condition evaluates to false.
An example of the `for` loop is given below -
**for.go**
```go
package main
import "fmt"
func main() {
sum := 0
for i := 0; i <= 10; i++ {
sum += i
}
fmt.Println("The sum of first 10 natural numbers is", sum)
}
```
Running the above program produces an output similar to the following output -
```
$ go run for.go
The sum of first 10 natural numbers is 55
```
You can use `continue` and `break` to adjust the loops flow
```go
// this code prints any odd numbers up to 5
for n := 0; n <= 10; n++ {
if n % 2 == 0 {
// if the number is even jump to the next n
continue
}
fmt.Println(n)
// if the number is 5 exit the loop
if n == 5 {
break
}
}
```
If you want to create an infinite loop just use `for { }`
```go
for {
// Whill loop until a condition breaks the loop
break // exit the loop
}
```
## Replacement for while-loop
To simulate while-loop of other languages, you can simply exclude the **init** and **post** statement:
```go
func main() {
num := 1
for num <= 1000 {
num *= 2
}
fmt.Println("The smallest power of 2 above 1000 is", num)
}
```

View File

@ -0,0 +1,70 @@
---
title: Go Methods
---
## Go Methods
Golang types can have methods. A method is a function with a special argument, the _receiver_.
```go
type Rectangle struct {
height, width int64
}
func (r Receiver) getArea() int64 {
return r.height * r.height
}
r := Rectangle{10, 20}
r.getArea() // 200
```
Here, type `Rectangle` has got a method called `getArea` that returns the area of the rectangle.
The receiver here is `r`.
This code is equivalent to:
```go
type Rectangle struct {
height, width int64
}
func getArea(r Receiver) int 64{
return r.height * r.height
}
r := Rectangle{10, 20}
getArea(r) // 200
```
Now the getArea method receives `r` as an argument, instead of a receiver. The functionality is equivalent.
### Pointer receiver
You can pass a pointer as a receiver:
```go
type MyInt int64
func (m *MyInt) setToZero() {
*m = MyInt(0)
}
m := MyInt(10)
m.setToZero() // m == 0
```
### Extension methods
If you want to create a method on a type defined in other package, e.g. `int` you can use a simple wrapper like this:
```go
type MyInt int64
func (m MyInt) add10() int64 {
return m + 10
}
m := MyInt(10)
m.add10() // 20
```
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
https://tour.golang.org/methods/1

View File

@ -0,0 +1,61 @@
---
title: Range
---
## Range
To iterate over a collection in Go, we can use the range.
Range differs from for-loops as the item in a collection is not accessed by an index.
If you want to access a specifc element in a collection, a for-loop is probably the better options.
Here is an example:
```go
package main
import "fmt"
func main() {
fruits := []string{"apple", "orange", "pear"}
for _, fruit := range fruits {
fmt.Println(fruit)
}
}
```
Will output:
````
apple
orange
pear
````
You might have noticed the blank identifer that was used.
The blank identifer (or the first variable returned from range) is the index of the item.
This is best suited when ranging over a map, so you can get the key and value:
```go
package main
import "fmt"
func main() {
kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
fmt.Printf("%s -> %s\n", k, v)
}
}
```go
Outputs:
````
a -> apple
b -> banana
````

View File

@ -0,0 +1,59 @@
---
title: Receive data with your web server
---
Once you've set up your web server and made sure it can serve some useful content, you might want to make it more interactive by letting it accept data. Let's get started by writing some code:
```go
package main
import (
"net/http"
"html/template"
)
type Page struct {
Name string
}
var page Page
func main() {
http.HandleFunc("/", servePage)
http.ListenAndServe(":8080", nil)
}
func servePage(writer http.ResponseWriter, reqest *http.Request) {
page.Name = request.FormValue("name")
template := template.New("sayHello")
template, _ = template.Parse("Hello {{.Name}}!")
template.Execute(writer, page)
}
```
Let's break this code down. First off all, we start by importing `net/http` for the web server and `html/template` for the templating. This article assumes you already know how to template in Go. If you don't know this yet, you should read the article on templating first.
Then we create a type called `PAGE`, with one slot in it called `NAME` (this is a `string`). We also create a global variable called `page` which is of type `PAGE`: the struct we just made.
In the `servePage` function there is one thing that is really important for this article: the `FormValue` method we run on the `request`.
Before we continue you first need to know how a `URL` is built. Let's take the following `URL` as an example:
```
https://google.com/search?q=free+code+camp
```
If you enter the `URL` above in your browser, it will perform a Google search for `free code camp`. The `URL` is built like this:
1. `https://` - this is the protocol
2. `google.com` - this is the domain name and port (in this case there is no port mentioned - so the browser uses the default port for the protocol)
3. `/search` - this is the path
4. `q=free+code+camp` - this is the `query`
The query is the part we talk about in this article. The Google server sees this `URL` and because of the attribute `q` in the query and the value of `q` - in this case `free+code+camp` - it knows where it should search for.
We can also apply this to our server. Let's fire up the program and navigate the browser to:
```
http://localhost:8080/?name=world
```
The response will be:
```
Hello world!
```
How does this work? Well, we gave the `FormValue` a parameter of `name`. This way `FormValue` knows we want the value of the `name` attribute in the query. In this case that is `world`, so the method returns `world`. That string is then put in the `page` variable and the template does the rest.
This is of course a really simple implementation of this function, but you could do a lot of things with it. For example: you could accept email addresses and let the program store those in a file.

View File

@ -0,0 +1,13 @@
---
title: Go Structs
---
## Go Structs
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/go/structs/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -0,0 +1,136 @@
---
title: Switch in Go
---
# Switch in Go
Go's switch statement is an alternative to `if`. It uses the following syntax:
```go
fruit := "apple"
switch fruit {
case "banana":
fmt.Printf("Yellow and long.")
case "apple":
fmt.Printf("Red and round.")
case "lemon":
fmt.Printf("Yellow and round.")
}
```
This program's output would be `Red and round.`.
First, we declare the variable `fruit` as `apple`. Then we use the `fruit` variable as the condition expression.
Go compares the value of `fruit` with the `cases` provided like this:
- fruit == "banana" (false)
- fruit == "apple" (true)
Notice `lemon` was not tested. After an evaluation returns true, no more cases are tried.
As with `if`, you can declare temporary variables on the switch`s condition expression:
```go
switch fruit := "apple"; fruit {
case "banana":
fmt.Printf("Yellow and long.")
case "apple":
fmt.Printf("Red and round.")
case "lemon":
fmt.Printf("Yellow and round.")
}
```
The variable `fruit` will not be accessible outside of the switch statement.
## Default and other cases
### Default
The `default` keyword is the fall back case when no other cases return true:
```go
switch fruit := "grape"; fruit {
case "banana":
fmt.Printf("Yellow and long.")
case "apple":
fmt.Printf("Red and round.")
case "lemon":
fmt.Printf("Yellow and round.")
default:
fmt.Printf("New fruit: %s!", fruit)
}
```
This program's output would be `New fruit: grape!`.
### Same action for different values
A comma separated list of values to compare the condition expression value to, with the same action.
```go
switch fruit := "lemon"; fruit {
case "banana", "lemon":
fmt.Printf("Yellow fruit.")
default:
fmt.Printf("This fruit is a color different than yellow.")
}
```
Output: `Yellow fruit.`.
### No expression
A switch with no expression means `switch true`. This is an alternate version to an else-if chain.
```go
fruit := "banana"
switch {
case fruit == "banana":
fmt.Printf("Yellow and long.")
default:
fmt.Printf("This is not a banana.")
}
```
This evaluates `true == (fruit == "banana")`, simpliefied to `true == true`, which returns true.
### Break
You can break code in a switch statement to skip any more code.
```go
appleColor := "green"
switch fruit := "apple"; fruit {
case "banana":
fmt.Printf("Yellow and long.")
case "apple":
if appleColor == "green" {
fmt.Printf("This apple is green!")
break
}
fmt.Printf("This apple is tasty!")
case "lemon":
fmt.Printf("Yellow and round.")
}
```
Output: `This apple is green!`.
### Fallthrough
Skip to the next case, whether its condition evaluates to true.
```go
switch fruit := "banana"; fruit {
case "banana":
fmt.Printf("Yellow and long.")
fallthrough
case "apple":
fmt.Printf("Red and round.")
case "lemon":
fmt.Printf("Yellow and round.")
}
```
Output: `Yellow and long.` AND `Red and round.`.

View File

@ -0,0 +1,25 @@
---
title: The Zero Value
---
## The Zero Value
Understanding some zero values inside Golang:
1. false for booleans
2. 0 for integers
3. 0.0 for floats
4. "" for strings
5. nil for
* pointers
* functions
* interfaces
* slices
* channels
* maps
Please, use short declaration operator as much as possible.
* Use var for:
* zero value
* package scope
### More Information

View File

@ -0,0 +1,64 @@
---
title: Using templates with your web server
---
When you have a web server, you might want to insert data into your responses. Let's see some code:
```go
package main
import (
"net/http"
"html/template"
)
type PAGE struct {
NAME string
}
var page PAGE
func main() {
page.NAME = "Mark"
http.HandleFunc("/", servePage)
http.ListenAndServe(":8080", nil)
}
func servePage(writer http.ResponseWriter, reqest *http.Request) {
template := template.New("sayHello")
template, _ = template.Parse("Hello {{.NAME}}!")
template.Execute(writer, page)
}
```
Now fire up this program and navigate your browser to:
```
http://localhost:8080/
```
The response will be:
```
Hello Mark!
```
But how does this work and what does the code do? Well, first of all we import the `net/http` package so we can run a web server. Then we import the `html/template` package. This enables a feature called templating; and that is where this article is about.
We also create a type called `PAGE`, which has one field called `NAME` as type `string`. We also create a global variable called `page` of type `PAGE`, the struct we just created. In the `main` function we give the `NAME` field of `page` a value of `Mark` - my name, but feel free to use your own name!
The `servePage` function is a bit difficult at first. Let's take it apart:
```go
func servePage(writer http.ResponseWriter, reqest *http.Request) {
// 1. Creating a template
template := template.New("sayHello")
// 2. Filling the template
template, _ = template.Parse("Hello {{.NAME}}!")
// 3. Executing the template
template.Execute(writer, page)
}
```
What do we do here? Let's see step by step:
1. We create a *template*. You need to enter a name, but it does not really matter what name you choose. Here I chose `sayHello`.
2. Then we fill the template with some text. Please take note of the `{{.NAME}}`.
3. Finally, we *execute* the template. This means that the template is filled out and sent to the client.
But how do we go from `{{.NAME}}` to `Mark`? Well, remember we used the `page` variable as a parameter to the `Execute` method? This method looks at the data in the template and sees `{{.NAME}}`. The `.NAME` indicates that it should look for a field called `NAME` inside the variable that was specified as a parameter when `Execute` was called. In this case it finds that field and it takes note of that the value is `Mark`. The `{{` and `}}` are telling `Execute` that it should replace `{{.NAME}}` with the value that it found. So the end result will become `Hello Mark!`.
You can have multiple fields and multiple `{{.XXX}}`'s. This is a really easy way you can insert data into responses, and you now know how to template in Go!

View File

@ -0,0 +1,61 @@
---
title: Variadic Functions
---
## Variadic Functions
Variadic functions are functions that can be called with any number of trailing arguments.
This is a useful feature when we are working on web-apps.
Sometimes we are not how many elements we will need to pass to the HTML templating engine.
Here are the basics on how varidic functions work:
```go
package main
import "fmt"
func printFruits(fruits ...string) {
for _, fruit := range fruits{
fmt.Println(fruit)
}
}
func main() {
printFruits("apple", "bannana")
printFruits("papaya", "coconut", "pear", "pineapple")
berries := []string{"blueberry", "strawberry", "raspberry"}
printFruits(berries...)
}
```
First, in printFruits we defined the number of arguments with [...string].
This tells Go that this function accepts any number of string arguments.
The first two calls to printFruits shows that the function will print each string, even if we are passing a different number of arguments.
```text
apple
bannana
...
papaya
coconut
pear
...
```
This will also work for slices.
To use a vardiac function with a slice, we add the training dots to the call.
```go
printFruits(berries...)
```
```text
blueberry
strawberry
raspberry
```