[go golang] Web Development with Go (Golang)

 

The Go language has excellent built-in support for web development and web app programming. There are packages to work with the generic functionalities for implementing networking and Internet protocols, making it easy to use functionality like the Google App engine. In this Go programming tutorial, we introduce some of the features of the Golang standard library that allow us to write code that seamlessly integrates with the web and can be used for creating websites and web applications.

How Does the Web Work?

Before we start learning the ins and outs of Go web development, let’s quickly detour and take a look at how the web actually works. The web – and networks in general – always works using the client-server principle. The client is a computer that requests a service via a URL and the server is a computer (or server) that serves the request. The URL (Uniform Resource Locator) is the address that decides which server the client wants to request service from.

In this process, the server usually responds back in the form of a web page, which the client displays in the browser. Therefore, for a normal user, any URL entered in the browser fetches a web page from some server. What actually happens is that, after you type the URL, the host part of the URL is sent to the DNS (Domain Name Server), which maps to the IP (Internet Protocol) address of the host.

Once the IP address is obtained, a TCP (Transmission Control Protocol) connection is set up. Understand that all of this “play” of Internet browsing (client request-server response) is defined by HTTP (HyperText Transfer Protocol) and the server that facilitates this is called an HTTP or web server. TCP/IP contains several protocols for different purposes, such as SMTP for Email service, FTP for file service, HTTP for web service, and so on.

Web Development in Go

Therefore, the browser sends HTTP requests through a TCP connection, and the server that receives the request, processes or handles it and replies back with an HTTP response. The HTTP response contains the code that makes up the web page. The browser renders the page according to the received code and then disconnects from the server.

Note that the DNS (Domain Name System) is the naming system for computer network services responsible for converting domain names to actual IP addresses.

Read: Intro to Socket Programming in Go

What Is Web Programming and Web Development?

To continue upon the above train of thought, the browser renders a page upon receiving the HTTP response from the server. The response consists of code, typically written in web development languages and scripting languages such as HTMLCSS, and JavaScript. HTML is responsible for constructing the page document, structure, and layout. CSS leverages the look and feel. JavaScript is also used to enhance the functionality of the web page and makes browsing more convenient for the end-user. The request sent from the HTTP client is processed by the server. This processing part is written in one or many server languages such as PHP, Java, C++, Golang, and so forth. Sometimes the processing server also requires a backend database. In that event, database access-specific code is also written, typically using the same language or a language that extends the primary programming language. Web development, therefore, includes writing code in one or all of these web development languages.

Web Development in Go and Golang

The Go programming language is one of the many high-level languages that can be used for web development. The criteria for choosing any one of them can include performance, convenience, learning curve, available libraries, and any other number of considerations. Although the end result is the same, the decisive factor is how quickly and conveniently we can create a web application. PHP, Java, and C# are all excellent and proven in this field. The standard library support of Go, however, makes web development particularly easy, convenient, and quick.

With Golang, web developers simply need the Go compiler and nothing else to get started developing web pages and web apps. The built-in features of Go already include a web server and the net/http package in the standard library, which provides the necessary functions required for working with the HTTP protocol. The HTTP client and HTTP server are part of this library. This makes web programming (at least to begin with ) hassle-free and quick. However, as you dive deeper, there are many twists and turns in web development where we have to use other libraries, languages, and even web frameworks, as well.

Read: Working with XML Files in Go

The Go Web Server

The stub web server of the net/http package delegates the handling of requests in our code. It follows the following four basic principles:

  • Request: user data request using POSTGETCOOKIE, and URL.
  • Response: response back to the client.
  • Connection: establish a TCP connection between the client and server.
  • Handler: processing of the request received (also business logic).

Web Development in Golang

Once the web server is up, it creates a listening socket at the specific port and waits for the connection request from the client. The process includes:

  • Listening socket is created and waits for client connection.
  • Accepts requests received from the client.
  • Process request: reads the HTTP header and checks if it is a POST method. Reads the message and passes it to the handler for processing and finally responds back to the client.

Go Web Server Example Code

Let us write some simple and minimal code to illustrate how to create a web server in Go. We will assume the Go compiler is installed properly on your system. Type the following (Linux) commands to begin:

$ mkdir webprojects
$ mkdir webprojects/project1
$ cd webprojects/project1
$ nano main.go

If you are using the Visual Code IDE, replace:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

$ nano main.go 

with:

$ code main.go

Next, type the following Go code to create the web server:

package main
import (
"fmt"
"net/http"
)
func greetHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>Welcome to my home page</h1>")
fmt.Fprintf(w, "Requested URL path = %s", r.URL.Path)
}
func main() {
http.HandleFunc("/", greetHandler)
fmt.Println("Starting server at port 9999...")
http.ListenAndServe(":9999", nil)
}
$ go run main.go

The server should start running. Open the browser and type the following into the address bar: http://localhost:9999, followed by pressing Enter. The browser should keep running. To stop it, just press Ctrl+C.

Read: Working with JSON Files in Go

Understanding the Go Web Server Code

ResponseWriter implements the io.Writer interface; as a result, it can be used with the functions from the fmt package. We can embed HTML code and print them in the client area of the browser using http.ResponseWriter.

The function HandleFunc registers the handler function named greetHandler for the given pattern in the defaultServeMux used by the server. ServeMux is the HTTP request multiplexer responsible for matching the incoming request against the registered pattern and calls the appropriate handler for the pattern. In our case the pattern is given “/”, which means a request to the URL http://localhost:9999 will be handled by the greetHandler function.

Add another handler, such as the thanksHandler function, as follows:

func thanksHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>Thanks. Visit again.</h1>")
}

Next, register this handler as well with func main:

func main() {
http.HandleFunc("/", greetHandler)
http.HandleFunc("/thanks", thanksHandler)
fmt.Println("Starting server at port 9999...")
http.ListenAndServe(":9999", nil)
}

Next, register this handler as well with func main:

func main() {
http.HandleFunc("/", greetHandler)
http.HandleFunc("/thanks", thanksHandler)
fmt.Println("Starting server at port 9999...")
http.ListenAndServe(":9999", nil)
}

Now, as you type the URL http://localhost:9999/thanks, this will invoke the thanksHandler.

The ListenAndServe listens on the TCP network address and then calls Serve with a handler to handle requests on incoming connections. Here the address value indicates the port number that the server will keep listening to for any incoming client request. The handler is typically nil, in which case the default ServeMux is used.

Final Thoughts on Go Web Development

The Golang creators are stalwarts in web technology, hence it is no surprise that the language has excellent standard library support for the Internet. For example, the textproto package implements generic support for text-based request-response protocols like HTTPNNTP, and SMTP. Here, we have only touched the tip of the iceberg. Even the http package has a lot of other functionalities, which we will explore in future Golang web development tutorials.

[출처] https://www.developer.com/languages/web-development-golang/

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
24 [rust] Learn Rust in under 10 mins 졸리운_곰 2023.06.28 67
23 [flutter/dart] Flutter fvm(Flutter Version Management) 사용하기 file 졸리운_곰 2023.06.23 62
22 [go golang] Golang Machine Learning file 졸리운_곰 2022.11.28 31
21 [go golang] A Quick / Short Example of using TFLite with Golang and a GANs Model file 졸리운_곰 2022.11.29 14
» [go golang] Web Development with Go (Golang) 졸리운_곰 2022.11.29 11
19 [rust] Rust 요약(메모리 관리) 졸리운_곰 2023.05.10 10
18 [flutter/dart] mac os x : fvm(Flutter Version Management) 설치 및 사용법 file 졸리운_곰 2023.07.01 8
17 [kotlin java] 이펙티브 코틀린 간단 정리 (Effective Kotlin) 졸리운_곰 2023.06.08 6
16 [go golang] Golang REST API 만들기 file 졸리운_곰 2023.01.03 5
15 [flutter/dart] [flutter] flutter_localizations 다국어 적용하는 방법 졸리운_곰 2023.07.02 4
14 [kotlin java] 코틀린 기본 문법 요약 정리 강좌 - [kotlin/cheat sheet] file 졸리운_곰 2023.06.08 4
13 [rust] Learn X in Y minutes : Y분 안에 X를 배우세요 졸리운_곰 2023.11.27 3
12 [kotlin java] [코틀린/Kotlin] 기초 문법 정리 졸리운_곰 2023.06.08 3
11 [go golang] Gin 소개 & 설치 (Introduction & Installation) file 졸리운_곰 2023.01.03 3
10 [flutter/dart] 플러터(Flutter) 다국어 대응하기 (Localization) file 졸리운_곰 2023.07.02 2
9 [rust programming] Rust 언어 튜토리얼 졸리운_곰 2023.05.04 2
8 [Kotlin] Eclipse를 이용한 Kotlin 작업환경 구성 file 졸리운_곰 2023.09.02 1
7 [kotlin] [Kotlin] 기본 - Null 처리 '? / ?. / !! / ?: / lateinit / lazy' file 졸리운_곰 2023.09.02 1
6 [flutter/dart] flutter - fvm 적용하기 (Futter Version Management) file 졸리운_곰 2023.06.24 1
5 [rust] Rust 요약(기초) 졸리운_곰 2023.05.10 1
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED