Go的http编程
- Go原生支持http,import (“net/http”)
- Go的http性能和nginx比较接近
- 几行代码能够实现一个web服务
http server
import (
"fmt"
"net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Println("handle hello")
fmt.Fprint(w, "hello")
}
func main() {
http.HandleFunc("/hello", hello)
err := http.ListenAndServe("127.0.0.1:8888", nil)
if err != nil {
fmt.Println("http listen failed")
}
}
http client
func main() {
res, err := http.Get("https://www.baidu.com/")
if err != nil {
fmt.Println("Get url failed:", err)
return
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("get data error:", err)
return
}
fmt.Println(string(data))
}
http head请求(监控网站或者服务是否正常)
var url = []string{
"http://www.baidu.com",
"http://www.1232.com",
"http://taobao.com",
}
func main() {
// 设置超时时间
c := http.Client{
Transport: &http.Transport{ // Transport 底层Tcp网络传输
Dial: func(network, addr string) (conn net.Conn, e error) { // Dial 跟服务端建立连接
timeout := time.Second * 2
return net.DialTimeout(network, addr, timeout)
},
},
}
for _, v := range url {
//res, err := http.Head(v)
res, err := c.Head(v)
if err != nil {
fmt.Printf("head %s failed,err%v\n:", v, err)
continue
}
fmt.Printf("head success, status:%v\n", res.Status)
}
}
表单处理
const form = `<html><body><form action="#" method="post" name="bar">
<input type="text" name="in"/>
<input type="text" name="in"/>
<input type="submit" value="Submit"/>
</form></body></html>`
func SimpleServer(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "<h1> hello world<h1>")
}
func FormServer(w http.ResponseWriter, request *http.Request) {
w.Header().Set("Content-Type", "text/html")
switch request.Method {
case "GET":
io.WriteString(w, form)
case "POST":
request.ParseForm()
io.WriteString(w, request.Form["in"][1])
io.WriteString(w, "\n")
io.WriteString(w, request.FormValue("in"))
}
}
func main() {
http.HandleFunc("/test1", SimpleServer)
http.HandleFunc("/test2", FormServer)
if err := http.ListenAndServe("127.0.0.1:8888", nil); err != nil {
fmt.Println("http listen server error")
}
}
http panic处理
func logPanics(handle http.HandlerFunc) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
defer func() {
if x := recover(); x != nil {
log.Printf("[%v] caught panic: %v", request.RemoteAddr, x)
}
}()
handle(writer, request)
}
}
func main(){
http.HandleFunc("/test1", logPanics(SimpleServer))
}
http_template
var myTemplate *template.Template
type Person struct {
Title string
Name string
Age int
}
func index(w http.ResponseWriter, r *http.Request) {
p := Person{
Title: "个人首页",
Name: "Demo",
Age: 18,
}
myTemplate.Execute(w, p)
}
func initTemplate(filename string) (err error) {
myTemplate, err = template.ParseFiles(filename)
if err != nil {
fmt.Println("parse file err:", err)
return
}
return
}
func logPanics(handle http.HandlerFunc) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
defer func() {
if x := recover(); x != nil {
log.Printf("[%v] caught panic: %v", request.RemoteAddr, x)
}
}()
handle(writer, request)
}
}
func main() {
initTemplate("D:/Go/src/new/day10/http_template/index.html")
http.HandleFunc("/index", logPanics(index))
err := http.ListenAndServe("127.0.0.1:8888", nil)
if err != nil {
fmt.Println("http listen error:", err)
}
}
模板if-else
<body>
{{if gt .Age 18}}
<p>old man {{.Name}}</p>
{{else}}
<p>young man {{.Name}}</p>
{{end}}
</body>
if 常见操作符
1、not 非
{{if not.condition}}
{{end}}
2、and 与
{{if and .condition1 .condition2}}
{{end}}
3、or 或
{{if or .condition1 .condition2}}
{{end}}
4、eq 等于
{{if eq .var1 .var2}}
{{end}}
5、ne 不等于
{{if ne .var1 .var2}}
{{end}}
6、lt 小于
{{if lt .var1 .var2}}
{{end}}
7、le 小于等于
{{if le .var1 .var2}}
{{end}}
8、gt 大于
{{if gt .var1 .var2}}
{{end}}
9、ge 大于等于
{{if ge .var1 .var2}}
{{end}}
模板循环
{{range .}}
{{if gt .Age 18}}
<p>hello, old man, {{.Name}}</p>
{{else}}
<p>hello,young man, {{.Name}}</p>
{{end}}
{{end}}