Webapps in Go (Suraj Patil) (z-library.sk, 1lib.sk, z-lib.sk)
Author: Suraj Patil
GO
No Description
📄 File Format:
PDF
💾 File Size:
910.6 KB
5
Views
0
Downloads
0.00
Total Donations
📄 Text Preview (First 20 pages)
ℹ️
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
📄 Page
1
(This page has no text content)
📄 Page
2
Webapps in Go the anti textbook Suraj Patil This book is for sale at http://leanpub.com/antitextbookGo This version was published on 2018-06-09 This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do. © 2016 - 2018 Suraj Patil
📄 Page
3
Tweet This Book! Please help Suraj Patil by spreading the word about this book on Twitter! The suggested tweet for this book is: I just bought Webapps in Go by @igeeko. The suggested hashtag for this book is #WebDevGoAntiTextbook. Find out what other people are saying about the book by clicking on this link to search for this hashtag on Twitter: #WebDevGoAntiTextbook
📄 Page
4
Akshay Agarwal: For introducing me to the FOSS world. Hrishikesh Nandedkar: For guiding me in the right direction.
📄 Page
5
Contents Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 System requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Install the Go tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 The toolchain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Hello, Go . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Why Go? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Variables & Data structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Underlying data structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Important points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 array, slice, map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Control statements and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Control statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Struct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Basics of Struct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Object-oriented . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 Concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 Managing the Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 Internal deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
📄 Page
6
CONTENTS Web Programming Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 HTTP Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 What is a template? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 Static Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 Basic web application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 Handling URLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Serving static files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 Homework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Designing our web app . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 The Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 Homework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 Using databases in Go . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Creating and configuring database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Installing sqlite driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Accessing the database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Importing driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Retrieving Result Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 Fetching Data from the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 How Scan() Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 Preparing Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 Single-Row Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 Modifying Data and Using Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 Statements that Modify Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 Working with Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 Using Prepared Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Prepared Statements And Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Avoiding Prepared Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Prepared Statements in Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 Parameter Placeholder Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Handling Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Errors From Iterating Resultsets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Errors From Closing Resultsets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Errors From QueryRow() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Identifying Specific Database Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 Handling Connection Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
📄 Page
7
CONTENTS Working with NULLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 Working with Unknown Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 The connection pool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 Surprises, Antipatterns and Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Resource Exhaustion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Large uint64 Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Connection State Mismatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 Database-Specific Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 Multiple Result Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 Invoking Stored Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 Multiple Statement Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Database Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 An Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 Homework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 Working with Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 CSRF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Input Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 Uploading files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 Sub templating . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 Homework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 Middlewares . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 Building an API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 JWT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 Making an API call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
📄 Page
8
CONTENTS Formatting a JSON document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 Testing API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 Writing an client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 Getting the token . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 Error handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 Advanced Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 Unit Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 Version Control Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Using git . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Branching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 Remote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
📄 Page
9
Installation If you know about installation or have installed Go, you can skip to Tools¹. This chapter is taken from install page² verbatim, except for the changes to be made to adapt to this book’s styling format. System requirements Go binary distributions are available for these supported operating systems and architectures. Please ensure your system meets these requirements before proceeding. If your OS or architecture is not on the list, you may be able to install from source or use gccgo instead Operating system Architectures Notes FreeBSD 8-STABLE or later amd64 Debian GNU/kFreeBSD not supported Linux 2.6.23 or later with glibc amd64, 386, arm CentOS/RHEL 5.x not supported; install from source for ARM Mac OS X 10.7 or later amd64 use the clang or gcc† that comes with Xcode‡ Windows XP or later amd64, 386 use MinGW gcc†. No need for cygwin or msys †gcc is required only if you plan to use cgo. ‡You only need to install the command line tools for Xcode. If you have already installed Xcode 4.3+, you can install it from the Components tab of the Downloads preferences panel. Install the Go tools If you are upgrading from an older version of Go you must first remove the existing version. Linux, Mac OS X, and FreeBSD tarballs Download the archive and extract it into /usr/local, creating a Go tree in /usr/local/go. For example: tar -C /usr/local -xzf go$VERSION.$OS-$ARCH.tar.gz ¹0.1tools.md ²https://golang.org/doc/install
📄 Page
10
Installation 2 Choose the archive file appropriate for your installation. For instance, if you are installing Go version 1.2.1 for 64-bit x86 on Linux, the archive you want is called go1.2.1.linux-amd64.tar.gz. (Typically these commands must be run as root or through sudo.) Add /usr/local/go/bin to the PATH environment variable. You can do this by adding this line to your /etc/profile (for a system-wide installation) or $HOME/.profile: export PATH=$PATH:/usr/local/go/bin Installing to a custom location The Go binary distributions assume they will be installed in /usr/local/go (or c:\Go under Windows), but it is possible to install the Go tools to a different location. In this case you must set the GOROOT environment variable to point to the directory in which it was installed. For example, if you installed Go to your home directory you should add the following commands to $HOME/.profile: export GOROOT=$HOME/go export PATH=$PATH:$GOROOT/bin Note: GOROOT must be set only when installing to a custom location. Mac OS X package installer Download the package file, open it, and follow the prompts to install the Go tools. The package installs the Go distribution to /usr/local/go. The package should put the /usr/local/go/bin directory in your PATH environment variable. You may need to restart any open Terminal sessions for the change to take effect. Windows The Go project provides two installation options for Windows users (besides installing from source): a zip archive that requires you to set some environment variables and anMSI installer that configures your installation automatically. MSI installer Open the MSI file and follow the prompts to install the Go tools. By default, the installer puts the Go distribution in c:Go. The installer should put the c:\Go\bin directory in your PATH environment variable. You may need to restart any open command prompts for the change to take effect.
📄 Page
11
Installation 3 Zip archive Download the zip file and extract it into the directory of your choice (we suggest c:Go). If you chose a directory other than c:\Go, you must set the GOROOT environment variable to your chosen path. Add the bin subdirectory of your Go root (for example, c:\Go\bin) to your PATH environment variable. Setting environment variables under Windows Under Windows, you may set environment variables through the “Environment Variables” button on the “Advanced” tab of the “System” control panel. Some versions ofWindows provide this control panel through the “Advanced System Settings” option inside the “System” control panel. Test your installation Check that Go is installed correctly by setting up a workspace and building a simple program, as follows. Create a directory to contain your workspace, $HOME/work for example, and set the GOPATH environment variable to point to that location. 1 $ export GOPATH=$HOME/work You should put the above command in your shell startup script ($HOME/.profile for example) or, if you use Windows, follow the instructions above to set the GOPATH environment variable on your system. Next, make the directories src/github.com/user/hello inside your workspace (if you use GitHub, substitute your user name for user), and inside the hello directory create a file named hello.go with the following contents: 1 package main 2 3 import "fmt" 4 5 func main() { 6 fmt.Printf("hello, world\n") 7 } Then compile it with the go tool:
📄 Page
12
Installation 4 1 $ go install github.com/user/hello The above command will put an executable command named hello (or hello.exe) inside the bin directory of your workspace. Execute the command to see the greeting: 1 $ $GOPATH/bin/hello hello, world If you see the “hello, world” message then your Go installation is working. Before rushing off to write Go code please read the How to Write Go Code document, which describes some essential concepts about using the Go tools. Uninstalling Go To remove an existing Go installation from your system delete the go directory. This is usually /usr/local/go under Linux, Mac OS X, and FreeBSD or c:\Go under Windows. You should also remove the Go bin directory from your PATH environment variable. Under Linux and FreeBSD you should edit /etc/profile or $HOME/.profile. If you installed Go with the Mac OS X package then you should remove the /etc/paths.d/go file. Windows users should read the section about setting environment variables under Windows. Getting help For real-time help, ask the helpful gophers in #go-nuts on the Freenode IRC server. The official mailing list for discussion of the Go language is Go Nuts. Report bugs using the Go issue tracker. Links -Next section³ ³0.1tools.md
📄 Page
13
Tools HTML: Brackets, a text editor for the web by Adobe. Go: Any IDE of your choice which has a Go language plugin. The toolchain The Go programming language comes with a set of tools along with the standard installation. gofmt Usage: gofmt main.go : Prints the formatted source code of main.go file on the console. gofmt -w main.go: Writes the formatted code in the file main.go gofmt -w Tasks: Runs gofmt on all the files in the folder Tasks. go fmt can be used in place of gofmt -w. Most IDEs can be configured to run gofmt on save. It is highly recommended to run gofmt before committing to version control. godoc It extracts documentation comments on all the Go projects present in $GOPATH/src, and the standard library present in $GOROOT. It has two interfaces: • Web: Usage: godoc -http=:6060 The documentation of net/http is present at localhost:6060/pkg/net/http. godoc also allows users to read the Go source code of the packages. Since Go is now implemented in Go itself, we can read the source code of Go language. Note: Verbose Flag
📄 Page
14
Tools 6 Depending on how much projects are in your $GOPATH, it’ll take time for godoc to get up and running, please use -v flag. Using the -v flag, we come to know when the server got up. • Commandline: Usage: godoc net/http This will provide the documentation of net/http on the terminal, like the man command. The catch here is that we need to know the exact library name. The packages where comments aren’t present show up as blank pages in godoc. Documentation The documentation covered by godoc is the documentation about the API, since only the exported functions have documentation comments in godoc. This documentation is different from the logic documentation. go test Go has testing support built into the language. For each code file file.go, the corresponding test cases should be present in a file named as file_test.go in the same folder. The Go compiler ignores all the *_test.go files while building the application. go build We can build our application using go build. It parses all the .go files except the *_test.go files in the entire folder and all sub folders along with imported libraries if any, and creates a statically linked binary. The binary name is the same as the project folder name, if we want a custom name we should use the -o flag. Example: go build -o tasks Build time By default, go build builds the entire application and the depending libraries, into a static binary and later throws all away. This results in rebuilding everything every single time go build is executed. For caching the library builds, use go install first and go build later. Cross compilation Go allows cross compilation. We have to pass the OS name as linux/darwin/windows as GOOS as shown in the below commands.
📄 Page
15
Tools 7 1 env GOOS=darwin GOARCH=386 go build -o tasks.app 2 env GOOS=windows GOARCH=386 go build -o tasks.exe go install Creates a statically linked binary and places it in $GOPATH/bin. Also creastes a .a file of the library and puts it in the $GOPATH/pkg folder. In future builds this library file will be reused until the underlying code is changed. For using tools built with Go like we use unix commands, we need to add $GOPATH/bin to the environment variable $PATH. Note: $PATH On Linux/Unix the $PATH environment variable is a list of directories which are known to have executables. When we call some executable from any terminal, the shell goes through all folders present in $PATH one at a time until it finds the executable. In Linux/Unix, this is done using: export PATH=$PATH:$GOPATH/bin. This line needs to be added to either .bashrc or .profile, whichever is being used by the shell. The profile files are present in the home folder. Do a cd ∼ and check for either of the files mentioned above. go run go run combines building and running the application in one command. It generates a binary in the temp folder and executes it. The binary file isn’t retained after the run. go get This is the package manager in Go. It internally clones the version control repository parameter passed to it, can be any local/remote git repository. It then runs go install on the library, making the library available in $GOPATH/pkg. If the repository doesn’t have any buildable files then go get might complain, but that happens after the repository is cloned. go clean This command is for cleaning files that are generated by compilers, including the following files:
📄 Page
16
Tools 8 1 _obj/ // old directory of object, left by Makefiles 2 _test/ // old directory of test, left by Makefiles 3 _testmain.go // old directory of gotest, left by Makefiles 4 test.out // old directory of test, left by Makefiles 5 build.out // old directory of test, left by Makefiles 6 *.[568ao] // object files, left by Makefiles 7 8 DIR(.exe) // generated by go build 9 DIR.test(.exe) // generated by go test -c 10 MAINFILE(.exe) // generated by go build MAINFILE.go Other commands Go provides more commands than those we’ve just talked about. 1 go fix // upgrade code from an old version before go1 to a new version after go1 2 go version // get information about your version of Go 3 go env // view environment variables about Go 4 go list // list all installed packages For details about specific commands, go help <command>. Links -Previous section⁴ -Next section⁵ ⁴0.0installation.md ⁵02.1IntroductionGo.md
📄 Page
17
Hello, Go Why Go? Go was built at Google, a company synonymous with Search and Distributed Computing, with Kubernetes. They wanted a language that was fast, worked well with automated code review and formatting and allowed a large team to write large scale software effectively, catered to the multi- core and networking era. All other major languages are at least a decade old. They were created in an era where memory was costly, where there were no massive clusters or multi-core processors. When switching from other languages to Go, it’ll be more or less frustrating to see the restrictions Go has. But as you tag along, the nuisances pay off. The language takes care of other things like formatting, and its goal is to provide a scalable approach to build the application over a long period of time. In the C family of languages, there are two factions: 1 public static void main() { 2 3 } vs 1 public static void main() 2 { 3 4 } The same can be said of Python spaces/tabs. Technically speaking, this was an unintended consequence of doing away with the semi colons, since the Go compiler adds semicolons at the end of each line, we can’t have the #2 definition in Go. This might seem to be a shallow problem, but when the codebase and team size grows, then it is difficult to maintain the consistency because of different user preferences. Anyone can write code these days, few can write elegant code. Other languages had to solve this problem as an afterthought.
📄 Page
18
Hello, Go 10 In Go they have been built into the language. Go isn’t just a language, it is an ecosystem and it caters to the entire software development cycle. It aims to provide the efficiency of a statically-typed compiled language with the ease of program- ming of a dynamic language. A list of features: 1. Unused imports/variables are compiler errors. 2. Semi-colons not needed, the compiler adds them at the line end. 3. A folder $GOPATH, as it is called contains all your Go code. 4. There is only one standard way to write Go code, use gofmt. 5. Batteries included standard library. 6. Compiled language, thus very fast. 7. Webapps can be written without a framework. 8. Has concurrency built in, just attach the word go before a function call to run it in its own goroutine. 9. Supports Unicode. 10. No language change from 1.0 to 1.7 Let’s start with the customary Hello World. First Program 1 package main 2 3 import "fmt" 4 5 func main() { 6 fmt.Printf("Hello, world or καλημ ρα κóσμ\n") 7 } It prints following information. 1 Hello, world or καλημ ρα κóσμ Explanation We import the format package, fmt for short. Write the main function of the main package and run the code. We can access only the Exported objects of any library in Go. Exported means that the names should start with a capital letter. The compiler will find the main function of the main package whenever we build or execute any Go code. We printed non ASCII characters. Go supports UTF-8 by default.
📄 Page
19
Hello, Go 11 The main package It is mandatory for each Go program to be a part of a package. The package can be main or not. Every package except main should be a distinct folder on the $GOPATH. Main is a special package for which having a folder on $GOPATH is optional. Building applications differs when we have a main folder and when we don’t. $GOPATH/src/github.com/thewhitetulip/Tasks • main.go • view.go or $GOPATH/src/github.com/thewhitetulip/Tasks • main/main.go • view.go In scenarios like this, we need to understand two different ways of executing the application • With the main folder: 1 [Tasks] $ go build main/main.go 2 [Tasks] $ ./main/main This will function correctly, because we are in the Tasks directory while executing our binary, all the templates and other files are present in this folder. • Without the main folder 1 [Tasks/main] $ go build main.go 2 [Tasks/main] $ ./main Here, we are in the Tasks/main directory, the binary will expect all the other files in the Tasks/main directory when they are in the Tasks directory, one level up. There can be only one main package & function per executable program. The main function takes no arguments passed and returns nothing. Links -Previous section⁶ -Next section⁷ ⁶0.1tools.md ⁷02.2VariablesDataStruct.md
📄 Page
20
Variables & Data structures Variables We use the keyword var to define a variable. The variable type comes after the variable name. 1 // define a variable with name "numberOfTimes" and type "int" 2 // the examples are of int, but you can use any other data type. 3 var numberOfTimes int 4 5 // define three variables which types are "int" 6 var var1, var2, var3 int 7 8 // define a variable with name "numberOfTimes”, type "int" 9 // and value "3" 10 var numberOfTimes int = 3 11 12 /* 13 Define three variables with type "int", and 14 initialize their values. 15 var1 is 1, var2 is 2, var3 is 3. 16 */ 17 var var1, var2, var3 int = 1, 2, 3 Variable declaration Shortcut 1 /* 2 Define three variables without type "type" and 3 without keyword "var", and initialize their values. 4 vname1 is v1vname2 is v2vname3 is v3 5 */ 6 vname1, vname2, vname3 := v1, v2, v3 := can only be used inside functions, for defining global variables we have to stick to using var. It throws a syntax error otherwise.
The above is a preview of the first 20 pages. Register to read the complete e-book.