- Go Web Development Cookbook
- Arpit Aggarwal
- 329字
- 2021-08-27 19:01:11
How it works…
Once we run the program, an HTTP server will start locally listening on port 8080. Opening http://localhost:8080 in a browser will display Hello World! from the server, as shown in the following screenshot:

Hello World!
Let’s understand what each line in the program means:
- package main: This defines the package name of the program.
- import ( "fmt" "log" "net/http" ): This is a preprocessor command that tells the Go compiler to include all files from fmt, log, and the net/http package.
- const ( CONN_HOST = "localhost" CONN_PORT = "8080" ): We declare constants in the Go program using the const keyword. Here we declared two constants—one is CONN_HOST with localhost as a value and another one is CONN_PORT with 8080 as a value.
- func helloWorld(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") }: This is a Go function that takes ResponseWriter and Request as an input and writes Hello World! on an HTTP response stream.
Next, we declared the main() method from where the program execution begins, as this method does a lot of things. Let’s understand it line by line:
- http.HandleFunc("/", helloWorld): Here, we are registering the helloWorld function with the / URL pattern using HandleFunc of the net/http package, which means helloWorld gets executed, passing (http.ResponseWriter, *http.Request) as a parameter to it whenever we access the HTTP URL with pattern /.
- err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil): Here, we are calling http.ListenAndServe to serve HTTP requests that handle each incoming connection in a separate Goroutine. ListenAndServe accepts two parameters—server address and handler. Here, we are passing the server address as localhost:8080 and handler as nil, which means we are asking the server to use DefaultServeMux as a handler.
- if err != nil { log.Fatal("error starting http server : ", err) return}: Here, we check whether there is a problem starting the server. If there is, then log the error and exit with a status code of 1.
推薦閱讀
- MERN Quick Start Guide
- 物聯(lián)網(wǎng)時(shí)代
- Wireshark網(wǎng)絡(luò)分析就這么簡(jiǎn)單
- C/C++串口通信:典型應(yīng)用實(shí)例編程實(shí)踐
- Microsoft Dynamics CRM 2011 Applications(MB2-868) Certification Guide
- 網(wǎng)管第一課:網(wǎng)絡(luò)操作系統(tǒng)與配置管理
- 網(wǎng)絡(luò)利他行為研究:積極心理學(xué)的視角
- 5G+區(qū)塊鏈
- 物聯(lián)網(wǎng)
- Architecting Data:Intensive Applications
- 網(wǎng)絡(luò)空間作戰(zhàn):機(jī)理與籌劃
- 網(wǎng)絡(luò)分析技術(shù)揭秘:原理、實(shí)踐與WinPcap深入解析
- 互聯(lián)網(wǎng)視覺(jué)設(shè)計(jì)(全彩慕課版)
- 從實(shí)踐中學(xué)習(xí)Kali Linux網(wǎng)絡(luò)掃描
- Learning IoT with Particle Photon and Electron