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

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
主站蜘蛛池模板: 禄劝| 庆阳市| 日喀则市| 大竹县| 息烽县| 绩溪县| 安溪县| 新民市| 滦南县| 甘孜县| 广河县| 安国市| 额尔古纳市| 大方县| 伊通| 庆云县| 桐城市| 西昌市| 水富县| 金塔县| 贵港市| 娄底市| 五河县| 伊川县| 开封市| 辽源市| 马边| 海南省| 项城市| 固安县| 呼图壁县| 万州区| 奉化市| 宣武区| 万源市| 乐亭县| 龙南县| 澎湖县| 江北区| 米林县| 航空|