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

How it works…

Once we run the program, the HTTP server will start locally listening on port 8080. Browsing http://localhost:8080 will show us an HTML form, as shown in the following screenshot:

Let’s understand the program we have written:

  • func login(w http.ResponseWriter, r *http.Request) { parsedTemplate, _ := template.ParseFiles("templates/login-form.html") parsedTemplate.Execute(w, nil) }: This is a Go function that accepts ResponseWriter and Request as input parameters, parses login-form.html, and returns a new template.
  • http.HandleFunc("/", login): Here we are registering a login function with the / URL pattern using HandleFunc of the net/http package, which means the login function gets executed every time we access the HTTP URL with the / pattern passing ResponseWriter and  Request as the parameters to it.
  • err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil): Here we are calling http.ListenAndServe to serve HTTP requests that handle each incoming connection in a separate Goroutine. ListenAndServe accepts two parameters—the server address and the handler—where the server address is localhost:8080 and the handler is nil.  
  • if err != nil { log.Fatal("error starting http server : ", err) return}: Here we check if there is a problem with starting the server. If there is, then log the error and exit with a status code of 1.
主站蜘蛛池模板: 余姚市| 安平县| 丰宁| 阿坝| 察隅县| 博罗县| 射阳县| 湄潭县| 庆安县| 宁乡县| 任丘市| 阳信县| 鹰潭市| 华亭县| 遂川县| 家居| 双辽市| 平遥县| 邵武市| 册亨县| 澎湖县| 图们市| 垫江县| 马关县| 灵台县| 札达县| 康马县| 凤庆县| 元氏县| 肥西县| 宜都市| 慈溪市| 北碚区| 桑日县| 贞丰县| 柳州市| 海伦市| 马边| 鹤庆县| 蓝山县| 响水县|