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

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.

主站蜘蛛池模板: 响水县| 无为县| 勐海县| 鸡东县| 措勤县| 峡江县| 南陵县| 临夏市| 新余市| 迁西县| 金堂县| 景谷| 夏邑县| 崇礼县| 广东省| 雅安市| 应用必备| 淮南市| 洪湖市| 丹巴县| 沙坪坝区| 故城县| 舟山市| 淮滨县| 玉林市| 蒲江县| 郧西县| 丹江口市| 兴化市| 寿光市| 鹰潭市| 金寨县| 闽清县| 友谊县| 铁力市| 大理市| 耒阳市| 进贤县| 准格尔旗| 龙江县| 永宁县|