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

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
主站蜘蛛池模板: 阳曲县| 九龙县| 闽清县| 丰顺县| 烟台市| 旌德县| 枣阳市| 普兰店市| 山东| 耒阳市| 安徽省| 浮山县| 平乐县| 曲麻莱县| 吉安县| 永胜县| 津南区| 齐齐哈尔市| 元阳县| 黑水县| 龙陵县| 凤翔县| 华宁县| 东阳市| 东安县| 都江堰市| 河津市| 磴口县| 榆社县| 乌苏市| 尚义县| 盘锦市| 鄂温| 巴塘县| 灵璧县| 高雄县| 上饶市| 土默特左旗| 康保县| 略阳县| 南雄市|