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

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.

主站蜘蛛池模板: 海口市| 广安市| 武功县| 德兴市| 罗江县| 于田县| 左权县| 连山| 桐梓县| 丹棱县| 光泽县| 白山市| 四平市| 睢宁县| 高陵县| 石狮市| 日喀则市| 宁远县| 邯郸县| 大足县| 新闻| 子长县| 进贤县| 洛浦县| 佳木斯市| 呼和浩特市| 化隆| 娄底市| 东乌| 苏州市| 长汀县| 永定县| 邓州市| 偏关县| 康乐县| 东乡县| 临夏市| 郯城县| 顺昌县| 义马市| 会昌县|