- Go Web Development Cookbook
- Arpit Aggarwal
- 154字
- 2021-08-27 19:01:12
How to do it…
In this recipe, we are going to create an HTTP server with a single handler, which will write Hello World! on an HTTP response stream and use a Gorilla CompressHandler to send all the responses back to the client in the .gzip format. Perform the following steps:
- To use Gorilla handlers, first we need to install the package using the go get command or copy it manually to $GOPATH/src or $GOPATH, as follows:
$ go get github.com/gorilla/handlers
- Create http-server-mux.go and copy the following content:
package main
import
(
"io"
"net/http"
"github.com/gorilla/handlers"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
func helloWorld(w http.ResponseWriter, r *http.Request)
{
io.WriteString(w, "Hello World!")
}
func main()
{
mux := http.NewServeMux()
mux.HandleFunc("/", helloWorld)
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT,
handlers.CompressHandler(mux))
if err != nil
{
log.Fatal("error starting http server : ", err)
return
}
}
- Run the program with the following command:
$ go run http-server-mux.go
推薦閱讀
- EJB 3.1從入門到精通
- 連接未來:從古登堡到谷歌的網絡革命
- 物聯網安全(原書第2版)
- JBoss EAP6 High Availability
- 2018網信發展報告
- 計算機網絡工程實用教程(第2版)
- Mastering JavaFX 10
- Building RESTful Web services with Go
- Microsoft Power Platform Enterprise Architecture
- 沖擊:5G如何改變世界
- 園區網絡架構與技術
- Selenium WebDriver 3 Practical Guide
- 工業以太網技術:AFDX/TTE網絡原理、接口、互連與安全
- 世界互聯網發展報告2021
- 從物聯到萬聯:Node.js與樹莓派萬維物聯網構建實戰