Documents to go linux

Documentation

The Go programming language is an open source project to make programmers more productive.

Go is expressive, concise, clean, and efficient. Its concurrency mechanisms make it easy to write programs that get the most out of multicore and networked machines, while its novel type system enables flexible and modular program construction. Go compiles quickly to machine code yet has the convenience of garbage collection and the power of run-time reflection. It’s a fast, statically typed, compiled language that feels like a dynamically typed, interpreted language.

Getting started

Installing Go

Instructions for downloading and installing Go.

Tutorial: Getting started

A brief Hello, World tutorial to get started. Learn a bit about Go code, tools, packages, and modules.

Tutorial: Create a module

A tutorial of short topics introducing functions, error handling, arrays, maps, unit testing, and compiling.

Tutorial: Developing a RESTful API with Go and Gin

Introduces the basics of writing a RESTful web service API with Go and the Gin Web Framework.

Writing Web Applications

Building a simple web application.

How to write Go code

This doc explains how to develop a simple set of Go packages inside a module, and it shows how to use the go command to build and test packages.

A Tour of Go

An interactive introduction to Go in three sections. The first section covers basic syntax and data structures; the second discusses methods and interfaces; and the third introduces Go’s concurrency primitives. Each section concludes with a few exercises so you can practice what you’ve learned. You can take the tour online or install it locally with:

This will place the tour binary in your GOPATH’s bin directory.

Using and understanding Go

Effective Go

A document that gives tips for writing clear, idiomatic Go code. A must read for any new Go programmer. It augments the tour and the language specification, both of which should be read first.

Editor plugins and IDEs

A document that summarizes commonly used editor plugins and IDEs with Go support.

Diagnostics

Summarizes tools and methodologies to diagnose problems in Go programs.

Managing dependencies

When your code uses external packages, those packages (distributed as modules) become dependencies.

Accessing databases

Tutorial: Accessing a relational database

Introduces the basics of accessing a relational database using Go and the database/sql package in the standard library.

Accessing relational databases

An overview of Go’s data access features.

Opening a database handle

You use the Go database handle to execute database operations. Once you open a handle with database connection properties, the handle represents a connection pool it manages on your behalf.

Executing SQL statements that don’t return data

For SQL operations that might change the database, including SQL INSERT , UPDATE , and DELETE , you use Exec methods.

Читайте также:  Простейший язык программирования для windows

Querying for data

For SELECT statements that return data from a query, using the Query or QueryRow method.

Using prepared statements

Defining a prepared statement for repeated use can help your code run a bit faster by avoiding the overhead of re-creating the statement each time your code performs the database operation.

Executing transactions

sql.Tx exports methods representing transaction-specific semantics, including Commit and Rollback , as well as methods you use to perform common database operations.

Cancelling in-progress database operations

Using context.Context, you can have your application’s function calls and services stop working early and return an error when their processing is no longer needed.

Managing connections

For some advanced programs, you might need to tune connection pool parameters or work with connections explicitly.

Avoiding SQL injection risk

You can avoid an SQL injection risk by providing SQL parameter values as sql package function arguments

Developing modules

Developing and publishing modules

You can collect related packages into modules, then publish the modules for other developers to use. This topic gives an overview of developing and publishing modules.

Module release and versioning workflow

When you develop modules for use by other developers, you can follow a workflow that helps ensure a reliable, consistent experience for developers using the module. This topic describes the high-level steps in that workflow.

Managing module source

When you’re developing modules to publish for others to use, you can help ensure that your modules are easier for other developers to use by following the repository conventions described in this topic.

Developing a major version update

A major version update can be very disruptive to your module’s users because it includes breaking changes and represents a new module. Learn more in this topic.

Publishing a module

When you want to make a module available for other developers, you publish it so that it’s visible to Go tools. Once you’ve published the module, developers importing its packages will be able to resolve a dependency on the module by running commands such as go get.

Module version numbering

A module’s developer uses each part of a module’s version number to signal the version’s stability and backward compatibility. For each new release, a module’s release version number specifically reflects the nature of the module’s changes since the preceding release.

Frequently Asked Questions (FAQ)

Answers to common questions about Go.

References

Package Documentation

The documentation for the Go standard library.

Command Documentation

The documentation for the Go tools.

Language Specification

The official Go Language specification.

Go Modules Reference

A detailed reference manual for Go’s dependency management system.

go.mod file reference

Reference for the directives included in a go.mod file.

The Go Memory Model

A document that specifies the conditions under which reads of a variable in one goroutine can be guaranteed to observe values produced by writes to the same variable in a different goroutine.

Release History

A summary of the changes between Go releases.

Codewalks

Guided tours of Go programs.

From the Go Blog

The official blog of the Go project, featuring news and in-depth articles by the Go team and guests.

Language

Packages

  • JSON and Go — using the json package.
  • Gobs of data — the design and use of the gob package.
  • The Laws of Reflection — the fundamentals of the reflect package.
  • The Go image package — the fundamentals of the image package.
  • The Go image/draw package — the fundamentals of the image/draw package.

Modules

  • Using Go Modules — an introduction to using modules in a simple project.
  • Migrating to Go Modules — converting an existing project to use modules.
  • Publishing Go Modules — how to make new versions of modules available to others.
  • Go Modules: v2 and Beyond — creating and publishing major versions 2 and higher.
  • Keeping Your Modules Compatible — how to keep your modules compatible with prior minor/patch versions.
Читайте также:  Windows антивирус полная версия

Tools

  • About the Go command — why we wrote it, what it is, what it’s not, and how to use it.
  • Debugging Go Code with GDB
  • Data Race Detector — a manual for the data race detector.
  • A Quick Guide to Go’s Assembler — an introduction to the assembler used by Go.
  • C? Go? Cgo! — linking against C code with cgo.
  • Godoc: documenting Go code — writing good documentation for godoc.
  • Profiling Go Programs
  • Introducing the Go Race Detector — an introduction to the race detector.

The Go Wiki, maintained by the Go community, includes articles about the Go language, tools, and other resources.

See the Learn page at the Wiki for more Go learning resources.

Talks

A Video Tour of Go

Three things that make Go fast, fun, and productive: interfaces, reflection, and concurrency. Builds a toy web crawler to demonstrate these.

Code that grows with grace

One of Go’s key design goals is code adaptability; that it should be easy to take a simple design and build upon it in a clean and natural way. In this talk Andrew Gerrand describes a simple «chat roulette» server that matches pairs of incoming TCP connections, and then use Go’s concurrency mechanisms, interfaces, and standard library to extend it with a web interface and other features. While the function of the program changes dramatically, Go’s flexibility preserves the original design as it grows.

Go Concurrency Patterns

Concurrency is the key to designing high performance network services. Go’s concurrency primitives (goroutines and channels) provide a simple and efficient means of expressing concurrent execution. In this talk we see how tricky concurrency problems can be solved gracefully with simple Go code.

Advanced Go Concurrency Patterns

This talk expands on the Go Concurrency Patterns talk to dive deeper into Go’s concurrency primitives.

See the Go Talks site and wiki page for more Go talks.

Non-English Documentation

See the NonEnglish page at the Wiki for localized documentation.

Источник

Download and install

Download and install Go quickly with the steps described here.

For other content on installing, you might be interested in:

  • Managing Go installations — How to install multiple versions and uninstall.
  • Installing Go from source — How to check out the sources, build them on your own machine, and run them.

1. Go download.

Click the button below to download the Go installer.

Don’t see your operating system here? Try one of the other downloads.

2. Go install.

Select the tab for your computer’s operating system below, then follow its installation instructions.

  1. Extract the archive you downloaded into /usr/local, creating a Go tree in /usr/local/go.

Important: This step will remove a previous installation at /usr/local/go, if any, prior to extracting. Please back up any data before proceeding.

For example, run the following as root or through sudo :

rm -rf /usr/local/go && tar -C /usr/local -xzf go1.14.3.linux-amd64.tar.gz

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

You can do this by adding the following line to your $HOME/.profile or /etc/profile (for a system-wide installation):

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

Verify that you’ve installed Go by opening a command prompt and typing the following command:

  • Confirm that the command prints the installed version of Go.
    1. Open the package file you downloaded and follow the prompts to install Go.
    Читайте также:  Автозагрузка интеллект windows 10

    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.

    Verify that you’ve installed Go by opening a command prompt and typing the following command:

  • Confirm that the command prints the installed version of Go.
    1. Open the MSI file you downloaded and follow the prompts to install Go.

    By default, the installer will install Go to Program Files or Program Files (x86) . You can change the location as needed. After installing, you will need to close and reopen any open command prompts so that changes to the environment made by the installer are reflected at the command prompt.

  • Verify that you’ve installed Go.
    1. In Windows, click the Start menu.
    2. In the menu’s search box, type cmd , then press the Enter key.
    3. In the Command Prompt window that appears, type the following command:
  • Confirm that the command prints the installed version of Go.
  • 3. Go code.

    You’re set up! Visit the Getting Started tutorial to write some simple Go code. It takes about 10 minutes to complete.

    Источник

    Установка Go на Linux

    После выхода первой версии Go решил просмотреть что он из себя представляет и сразу же возникли трудности с установкой. После прочтения документации все же получилось установить. Хочу поделиться проделанными шагами на пути к установке Go на Linux, в моем случае Ubuntu 11.10.

    Есть конечно онлайн компилятор, но все таки во времена отсутствия подключения он нам не подойдет. Итак, на Ubuntu (и как говориться в документации на Debian) установку можно произвести из стандартных репозиториев, гду нужный нам пакет имеет название golang. Но насторожило следующие предложение «But there are still some minor issues being worked out. For now we will stick to the installation from source».

    Итак, начнем:

    1. Первым делом следует установить Python:
      apt-get install python-setuptools python-dev build-essential
      После чего уже можно устанавливать, тот самый Mercurial, о котором идеться в документации (для получения команды hg):
      sudo easy_install mercurial
    2. Go написан на С, поэтому нам понадобятся инструментальные средства C следующие пакеты:
      • bison — анализатор генератора
      • gcc — набор компиляторов
      • libc6-dev — стандартные библиотеки С
      • ed — текстовый редактор
      • gawk — интерпретатор
      • make — утилита для компиляции

      Устанавливаем:
      sudo apt-get install bison ed gawk gcc libc6-dev make

    3. Далее устанавливаем переменой GOROOT каталог где будет хранится корневая папка Go. В моем случае это выглядело так:
      export GOROOT=/home/bytex/go
    4. Качаем исходники в нашу папку:
      hg clone -r release https://go.googlecode.com/hg/ $GOROOT
    5. Ну и собственно компилируем и устанавливаем Go:
      cd $GOROOT/src
      ./all.bash
    6. В общем, все. После установки вывелось сообщение
      ALL TESTS PASSED


    Installed Go for linux/386 in /home/bytex/go
    Installed commands in /home/bytex/go/bin

    Надеюсь все нормально:)

    Теперь конечно время для написания первой программы Hello, world!.
    И собственно спасибо Miek’у Gieben’у и його книге.

    О песочнице

    Это «Песочница» — раздел, в который попадают дебютные посты пользователей, желающих стать полноправными участниками сообщества.

    Если у вас есть приглашение, отправьте его автору понравившейся публикации — тогда её смогут прочитать и обсудить все остальные пользователи Хабра.

    Чтобы исключить предвзятость при оценке, все публикации анонимны, псевдонимы показываются случайным образом.

    О модерации

    Не надо пропускать:

    • рекламные и PR-публикации
    • вопросы и просьбы (для них есть Хабр Q&A);
    • вакансии (используйте Хабр Карьеру)
    • статьи, ранее опубликованные на других сайтах;
    • статьи без правильно расставленных знаков препинания, со смайликами, с обилием восклицательных знаков, неоправданным выделением слов и предложений и другим неуместным форматированием текста;
    • жалобы на компании и предоставляемые услуги;
    • низкокачественные переводы;
    • куски программного кода без пояснений;
    • односложные статьи;
    • статьи, слабо относящиеся к или не относящиеся к ней вовсе.

    Источник

    Оцените статью