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

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
主站蜘蛛池模板: 荔波县| 宁强县| 祁阳县| 边坝县| 济阳县| 和静县| 怀化市| 大埔区| 全椒县| 美姑县| 图木舒克市| 凌云县| 武义县| 怀集县| 普兰店市| 沙洋县| 辛集市| 如东县| 钦州市| 宁化县| 连平县| 伊春市| 泰兴市| 南安市| 孝义市| 山丹县| 永福县| 商丘市| 鱼台县| 焦作市| 芜湖市| 榆中县| 明溪县| 黄陵县| 河南省| 灵丘县| 阿拉善左旗| 新晃| 景德镇市| 施秉县| 乾安县|