官术网_书友最值得收藏!

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:

  1. 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
  1. 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
}
}
  1. Run the program with the following command:
$ go run http-server-mux.go
主站蜘蛛池模板: 丹巴县| 阿城市| 依兰县| 温州市| 镇宁| 宜章县| 密山市| 若尔盖县| 鹤峰县| 襄垣县| 富顺县| 女性| 封丘县| 军事| 大足县| 阜城县| 沾化县| 独山县| 黑龙江省| 英德市| 盐津县| 云浮市| 连州市| 延津县| 淅川县| 衡山县| 齐河县| 民权县| 河津市| 枣庄市| 陆丰市| 左贡县| 连平县| 七台河市| 东乌珠穆沁旗| 新龙县| 杨浦区| 峨山| 外汇| 湘潭县| 盖州市|