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

Understanding Go's net/http package

Go's net/http package deals with HTTP client and server implementations. Here, we are mainly interested in the server implementation. Let us create a small Go program called basicHandler.go that defines the route and a function handler:

package main
import (
"io"
"net/http"
"log"
)
// hello world, the web server
func MyServer(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "hello, world!\n")
}
func main() {
http.HandleFunc("/hello", MyServer)
log.Fatal(http.ListenAndServe(":8000", nil))
}

This code does the following things: 

  1. Create a route called  /hello
  2. Create a handler called MyServer.
  3. Whenever the request comes on the route (/hello), the handler function will be executed.
  4. Write hello, world to the response.
  5. Start the server on port 8000. ListenAndServe returns error if something goes wrong. So log it using log.Fatal.
  6. The http package has a function called HandleFunc, using which we can map an URL to a function.
  1. Here, w is a response writer. A ResponseWriter interface is used by an HTTP handler to construct an HTTP response.
  2. req is a request object, which deals with all the properties and methods of an HTTP request.

Use the log function to debug potential errors. The ListenAndServe function returns an error if there are any.

主站蜘蛛池模板: 顺昌县| 克拉玛依市| 阳春市| 晋江市| 吴江市| 青冈县| 宜良县| 郑州市| 凤阳县| 巴楚县| 武乡县| 宜州市| 兴安盟| 乌恰县| 如皋市| 岳池县| 大名县| 和龙市| 墨脱县| 翁牛特旗| 齐齐哈尔市| 江永县| 荣昌县| 亚东县| 新干县| 芜湖市| 红安县| 凤凰县| 石棉县| 田林县| 汉寿县| 西乡县| 鄂温| 呼玛县| 二连浩特市| 平南县| 平凉市| 金塔县| 沐川县| 田阳县| 府谷县|