Go之路(二十八):Http编程
Http编程
go里面的http模块都是已经封装好的,在net/http里面
几行代码实现web服务:
package main
import(
"fmt"
"net/http"
)
func Hello(w http.ResponseWriter, request *http.Request){
fmt.Println("???") // 后台打印
fmt.Fprintf(w, "hello2") //前端打印
}
func Login(w http.ResponseWriter, request *http.Request){
// fmt.Println("hello") // 后台打印
fmt.Fprintf(w, "123123") //前端打印
}
func main() {
http.HandleFunc("/", Hello)
http.HandleFunc("/login/", Login)
err := http.ListenAndServe("0.0.0.0:8000", nil)
if err != nil{
fmt.Println(err)
}
}
另外,如果panic需要捕获,当项目规模比较大的时候,不能在每个函数前面都写一个捕获panic的功能,所以需要重新封装一个函数
package main
import(
"fmt"
"log"
"net/http"
)
func Hello(w http.ResponseWriter, request *http.Request){
fmt.Println("???") // 后台打印
fmt.Fprintf(w, "hello2") //前端打印
}
func Login(w http.ResponseWriter, request *http.Request){
// fmt.Println("hello") // 后台打印
fmt.Fprintf(w, "123123") //前端打印
}
func logPanic(handler http.HandlerFunc) http.HandlerFunc{
return func(w http.ResponseWriter, request *http.Request){
defer func(){
if err:=recover();err != nil{
log.Printf("%v panic: %v", request.RemoteAddr,err)
}
}()
handler(w,request)
}
}
func main() {
http.HandleFunc("/", logPanic(Hello))
http.HandleFunc("/login/", logPanic(Login))
err := http.ListenAndServe("0.0.0.0:8000", nil)
if err != nil{
fmt.Println(err)
}
}
渲染模板:使用text/template,ParseFiles方法
package main
import(
"fmt"
"log"
"net/http"
"text/template"
)
type Person struct{
Name string
Age int
}
func Hello(w http.ResponseWriter, request *http.Request){
tem,err:= template.ParseFiles("C:/Users/邓磊/Desktop/go/src/day11/http/index.html")
if err != nil{
fmt.Println(err)
}
p1 := Person{
Name:"tom",
Age:13,
}
if err:= tem.Execute(w, p1);err !=nil{
fmt.Println(err)
}
}
func Login(w http.ResponseWriter, request *http.Request){
// fmt.Println("hello") // 后台打印
fmt.Fprintf(w, "123123") //前端打印
}
func logPanic(handler http.HandlerFunc) http.HandlerFunc{
return func(w http.ResponseWriter, request *http.Request){
defer func(){
if err:=recover();err != nil{
log.Printf("%v panic: %v", request.RemoteAddr,err)
}
}()
handler(w,request)
}
}
func main() {
http.HandleFunc("/", logPanic(Hello))
http.HandleFunc("/login/", logPanic(Login))
err := http.ListenAndServe("0.0.0.0:8000", nil)
if err != nil{
fmt.Println(err)
}
}
模板语法---if:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>hello </p>
<p>{{.}}</p>
<p>{{.Name}}</p>
{{if gt .Age 18}}
<p>成年人{{.Age}}</p>
{{else}}
<p>未成年人{{.Age}}</p>
{{end}}
</body>
</html>

浙公网安备 33010602011771号