Почему язык программирования Go?

Go — это популярный язык программирования, который широко используется в отрасли для создания различных приложений, включая веб-серверы, сетевые инструменты и системные утилиты. Go известен своей простотой, эффективностью и поддержкой параллелизма, что делает его подходящим для создания масштабируемых высокопроизводительных систем.

Go используется многими компаниями и организациями, в том числе:

  1. Google: Google использует Go в ряде своих внутренних систем, включая платформу оркестровки контейнеров Kubernetes и поисковую систему Google Search.
  2. Netflix: Netflix использует Go в ряде своих систем, включая конвейер данных и систему рекомендаций.
  3. Dropbox: Dropbox использует Go в ряде своих сервисов, включая механизм синхронизации файлов и серверную инфраструктуру.
  4. Uber: Uber использует Go в ряде своих систем, включая распределенное хранилище данных и механизм маршрутизации.

В целом, Go — популярный язык программирования, который широко используется в отрасли благодаря своей простоте, эффективности и поддержке параллелизма. Он используется многими компаниями и организациями для создания различных приложений и систем.

Давайте создадим простое веб-приложение.

Установите GoLang

Первый шаг к началу работы с Go — установить его на свой компьютер. Вы можете скачать и установить Go с официального сайта (https://golang.org/).

Создать каталог проекта

Для начала нам нужно создать каталог с именем gowebapp внутри папки src в GOPATH. Если папка «src» еще не существует, мы должны сначала создать ее. После его создания мы можем приступить к созданию каталога «gowebapp».

Откройте терминал и используйте следующие команды:

cd go        
mkdir src    
cd src          
mkdir gowebapp
cd gowebapp
  1. cd go: Эта команда изменяет текущий рабочий каталог на каталог с именем «go».
  2. mkdir src: Эта команда создает новый каталог с именем «src» в текущем рабочем каталоге.
  3. cd src: Эта команда изменяет текущий рабочий каталог на только что созданный каталог src.
  4. mkdir gowebapp: Эта команда создает новый каталог с именем gowebapp в текущем рабочем каталоге (который теперь называется src).
  5. cd gowebapp: Эта команда изменяет текущий рабочий каталог на только что созданный каталог gowebapp.

Внутри каталога мы должны создать файл main.go, который будет основным файлом для нашего приложения, и написать несколько строк кода.

package main

import (
 "fmt"
 "gowebapp/handlers"  // Import the handlers package
 "log"
 "net/http"
 "os"
)

// Main program starts here
func main() {
 // Handling Routes
 // Set up a route for the index page
 http.HandleFunc("/", handlers.IndexHandler)
 // Set up a route for the task page
 http.HandleFunc("/task", handlers.TaskHandler)

 // Use environment variable "PORT" or otherwise assign
 port := os.Getenv("PORT")
 if port == "" {
  port = "8080"
  log.Printf("This port is %s", port)
 }

 // Log the port and the localhost address
 log.Printf("Listening on port %s", port)
 log.Printf("Open http://localhost:%s in the browser", port)

 // Create server or exit
 log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}

Добавить обработчики

Я предпочитаю организовывать свой код, разделяя его на несколько файлов, поэтому я хочу создать новый каталог с именем «handlers» и внутри этого каталога я создам файл с именем handlers.go. Это позволит мне организовать мой код и поддерживать его организованность по мере роста моего проекта.

package handlers

import (
 "net/http"
)

// IndexHandler handles requests to the index page
// It takes in a ResponseWriter and Request as arguments
func IndexHandler(w http.ResponseWriter, r *http.Request) {

 // If the request URL is not '/', return a 404 not found error
 if r.URL.Path != "/" {
  http.NotFound(w, r)
  return
 }

 // Create a Home struct and pass it to the renderTemplateHome function
 h := &Home{
  HomeTitle:  "Go Lang web page",
  Name:       "Anish",
  Profession: "Developer",
  Country:    "USA",
 }
 renderTemplateHome(w, "index", h)

 // If the Home struct is nil, return a 500 internal server error
 if h != nil {
  w.WriteHeader(http.StatusInternalServerError)
 }
}

// TaskHandler handles requests to the task page
// It takes in a ResponseWriter and Request as arguments
func TaskHandler(w http.ResponseWriter, r *http.Request) {
 // Create a Task struct and pass it to the renderTemplateTask function
 t := &Task{
  TaskNumber: "One",
  Title:      "Complete documentation",
  Due:        "jan 10, 2023",
 }
 renderTemplateTask(w, "task", t)

 // If the Task struct is nil, return a 500 internal server error
 if t != nil {
  w.WriteHeader(http.StatusInternalServerError)
 }
}

Создайте шаблоны для отображения результатов

На данный момент мы создали базовое приложение, которое отправляет ответ при запуске с помощью команды go run main.go. Однако это очень простое веб-приложение, и мы хотим сделать больше с GoLang. Для этого мы создадим файл HTML с именем index.html в папке с именем templates.

mkdir templates
cd templates
index.html
task.html
  1. mkdir templates: Эта команда создает новый каталог с именем «templates».
  2. cd templates: Эта команда изменяет текущий рабочий каталог на только что созданный каталог «templates».
  3. index.html: Эта команда создает новый файл с именем index.html в текущем рабочем каталоге (который теперь называется templates).
  4. task.html: Эта команда создает новый файл с именем «task.html» в текущем рабочем каталоге (который по-прежнему является «templates»).

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AnishInTech - {{.HomeTitle}}</title>
    <style type="text/css">
        body { 
            padding: 50px; // Add padding to the body element
            align-items: center; // Align the items in the center
            font-size: 15px; // Set the font size to 15px
            font-style: italic; // Set the font style to italic
        }
        li{
            color: #00B7FF; // Set the color of the li elements to a blue color
        }

    </style>
</head>
<body>
    <h1> Hello From my first Go Lang application</h1>
    <div>
        <!-- Display the values of the Name, Profession, and Country fields -->
        <li class="ans"><b>Name</b>:{{.Name}}</li>
        <li><b>Profession</b>:{{.Profession}}</li>
        <li><b>Country</b>:{{.Country}}</li>
        <!-- Link to the task page -->
        <a href="/task">Go to task page</a>
    </div>
</body>
</html>

task.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Task</title>

    <style type="text/css">
        body {
            background-color: green; // Set the background color to green
            align-items: center; // Align the items in the center
            color: red; // Set the text color to red
            padding: 50px; // Add padding to the body element
            font-size: 15px; // Set the font size to 15px
            font-style: italic; // Set the font style to italic
        }
        ul{
        list-style-type: circle; // Use circles as the list style
    }  
    </style>
    
</head>
<body>
    <h1> Here are the few task to complete</h1>
    <ul>
        <!-- Display the value of the TaskNumber field -->
        <h2><b>Task</b>:{{.TaskNumber}}</h2>
        <!-- Display the values of the Title and Due fields -->
        <li>Title:{{.Title}}</li>
        <li>Due Date:</b>:{{.Due}}</li>
        
      </ul>
</body>
</html>

Создайте .go file для рендеринга шаблонов:

Теперь мы создадим еще один файл с именем renderTemplate.go, который будет отвечать за отображение представлений.

package handlers

import (
 "html/template"
 "net/http"
)

// parse template files
var homeTemplates = template.Must(template.ParseFiles("templates/index.html"))
var taskTemplates = template.Must(template.ParseFiles("templates/task.html"))

// Home is a struct used to store the data needed for the Home template
type Home struct {
 HomeTitle  string
 Name       string
 Profession string
 Country    string
}

// Task is a struct used to store the data needed for the Task template
type Task struct {
 TaskNumber string
 Title      string
 Due        string
}

// renderTemplateHome is a custom function that takes the file name of a template HTML file and a pointer to a Home struct
// It writes the HTML template to the ResponseWriter, using the data from the Home struct
func renderTemplateHome(w http.ResponseWriter, tmp string, h *Home) {
 err := homeTemplates.ExecuteTemplate(w, tmp+".html", h)
 if err != nil {
  http.Error(w, err.Error(), http.StatusInternalServerError)
 }
}

// renderTemplateTask is a custom function that takes the file name of a template HTML file and a pointer to a Task struct
// It writes the HTML template to the ResponseWriter, using the data from the Task struct
func renderTemplateTask(w http.ResponseWriter, tmp string, t *Task) {
 err := taskTemplates.ExecuteTemplate(w, tmp+".html", t)
 if err != nil {
  http.Error(w, err.Error(), http.StatusInternalServerError)
 }
}

Заключение

В заключение мы узнали, как создать простое веб-приложение на GoLang. GoLang — популярный язык программирования, известный своей простотой и удобством использования, а также возможностью одновременного запуска нескольких процессов. Благодаря синтаксису, подобному C, и скомпилированной структуре, которая делает его эффективным, GoLang широко используется такими компаниями, как Netflix, Uber и Google, для создания веб-приложений, инструментов командной строки и других типов программного обеспечения. Мы надеемся, что это руководство помогло вам лучше понять GoLang и то, как его можно использовать для создания эффективного и действенного программного обеспечения.

Вы можете присоединиться ко мне в программировании, заглянув на мой канал YouTube AnishInTech — YouTube

Спасибо, что следите за нами!