Http编程
-
-
Go的http服务性能和nginx比较接近
-
几行代码就可以实现一个web服务
import ( "fmt" "net/http" ) func Hello(w http.ResponseWriter, r *http.Request) { fmt.Println("handle hello") fmt.Fprint(w, "hello") } func Login(w http.ResponseWriter, r *http.Request) { fmt.Println("handle hello") fmt.Fprint(w, "login") } func main() { http.HandleFunc("/", Hello) // 匹配路由,执行对应的方法 http.HandleFunc("/login", Login) err := http.ListenAndServe("127.0.0.1:8000", nil) if err != nil { fmt.Println("http listen failed") } }
import ( "fmt" "io/ioutil" "net/http" ) func main() { resp, err := http.Get("https://www.baidu.com/") if err != nil { fmt.Println("get err:", err) return } bytes, e := ioutil.ReadAll(resp.Body) if e != nil { fmt.Println("get data err:", e) return } // 打印获取的结果 fmt.Println(string(bytes)) }
import ( "fmt" "net" "net/http" "time" ) var url = []string{ "https://www.baidu.com", "http://google.com", "http://taobao.com", } func main() { for _, v := range url { // 自定义超时时间 2秒 c := http.Client{ Transport: &http.Transport{ Dial: func(network, addr string) (net.Conn, error) { timeout := time.Second * 2 return net.DialTimeout(network, addr, timeout) }, }, } // 请求 resp, err := c.Head(v) if err != nil { fmt.Printf("head %s faild, err: %v\n", v, err) continue } fmt.Printf("head success, status: %v\n", resp.Status) } }
import ( "fmt" "log" "net/http" ) func Hello(w http.ResponseWriter, r *http.Request) { fmt.Println("handle hello") fmt.Fprint(w, "hello") } func Login(w http.ResponseWriter, r *http.Request) { fmt.Println("handle hello") fmt.Fprint(w, "login") } func main() { http.HandleFunc("/", Panics(Hello)) // 匹配路由,执行对应的方法 http.HandleFunc("/login", Panics(Login)) err := http.ListenAndServe("127.0.0.1:8000", nil) if err != nil { fmt.Println("http listen failed") } } // 错误处理函数 func Panics(handle http.HandlerFunc) http.HandlerFunc { return func(writer http.ResponseWriter, request *http.Request) { // 出错走这里 defer func() { if e := recover(); e != nil { log.Printf("[%v] caught panic: %v", request.RemoteAddr, e) } }() // 正常执行 handle(writer, request) } }
go
import ( "fmt" "html/template" "os" ) type Person struct { Name string age int } func main() { // 读取html文件 temp, e := template.ParseFiles("src/go_dev/template/main/index.html") if e != nil { fmt.Println("parse file err:", e) return } person := Person{Name: "Marry", age: 18} // 将person对象传入进行渲染 if err := temp.Execute(os.Stdout, person); err != nil { fmt.Println("There was an error:", err.Error()) } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!-- 通过{{.Name}}获取person里面的name,.就表示person对象 --> <h1>hello, {{.Name}}</h1> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{if gt .Age 18}} <p>hello 18</p> {{else}} <p>hello 19</p> {{end}} </body> </html>
使用with可以将指定的变量用.代替
{{with .Name}} <!-- 此时的{{.}}就是{{.Name}} --> <p>{{.}}</p> {{end}}
{{range .}} <p>{{.Name}}</p> {{end}}