Go原生支持http。import("net/http")
Go的http服务性能和nginx比较接近
几行代码就可以实现一个web服务
服务端http
package main import (
"fmt"
"net/http"
) func Hello(w http.ResponseWriter, r *http.Request) {
fmt.Println("handle hello")
fmt.Fprintf(w, "hello")
}
func Login(w http.ResponseWriter, r *http.Request) {
fmt.Println("handle login")
fmt.Fprintf(w, "login....")
} func main() {
http.HandleFunc("/", Hello)
http.HandleFunc("/user/login", Login)
err := http.ListenAndServe("127.0.0.1:8800", nil)
if err != nil {
fmt.Println("htpp listen failed")
}
}
http客户端
package main import (
"fmt"
"io/ioutil"
"net/http"
) func main() {
res, err := http.Get("https://www.baidu.com/")
if err != nil {
fmt.Println("get err:", err)
return
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("get data err:", err)
return
}
fmt.Println(string(data))
}
http_head
package main import (
"fmt"
"net/http"
) var url = []string{
"http://www.baidu.com",
"http://google.com",
"http://taobao.com",
} func main() {
for _, v := range url {
res, err := http.Head(v)
if err != nil {
fmt.Printf("head %s failed,err:%v\n", v, err)
continue
}
fmt.Printf("head succ,status:%v\n", res.Status)
}
}
http_head自定义超时写法
package main import (
"fmt"
"net"
"net/http"
"time"
) var url = []string{
"http://www.baidu.com",
"http://google.com",
"http://taobao.com",
} func main() {
for _, v := range url {
//超时写法
c := http.Client{
Transport: &http.Transport{
Dial: func(network, addr string) (net.Conn, error) {
timeout := time.Second *
return net.DialTimeout(network, addr, timeout)
},
},
}
resp, err := c.Head(v)
if err != nil {
fmt.Printf("head %s failed,err:%v\n", v, err)
continue
}
fmt.Printf("head succ,status:%v\n", resp.Status)
}
}
http_form写法
package main import (
"io"
"log"
"net/http"
) 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, request *http.Request) {
io.WriteString(w, "hello,world")
panic("test test")
}
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", logPanics(SimpleServer))
http.HandleFunc("/test2", logPanics(FormServer))
if err := http.ListenAndServe(":8088", nil); err != nil {
}
}
//捕获,错误处理
func logPanics(handle http.HandlerFunc) http.HandlerFunc {
return func(write http.ResponseWriter, request *http.Request) {
defer func() {
if x := recover(); x != nil {
log.Printf("[%v]caught panic:%v", request.RemoteAddr, x)
}
}()
handle(write, request) //这里才是
}
}
http_template,模板写法
package main import (
"fmt"
"os"
"text/template"
) type Person struct {
Name string
age string
Title string
} func main() {
t, err := template.ParseFiles("d:/project/src/go_dev/day10/http_form/index.html")
if err != nil {
fmt.Println("parse file err:", err)
return
}
p := Person{Name: "Mary", age: "", Title: "我的个人网站"}
if err := t.Execute(os.Stdout, p); err != nil {
fmt.Println("There was an error:", err.Error())
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{.Title}}</title>
</head>
<body>
<p>hello,{{.Name}}</p>
<p>{{.}}</p>
</body>
</html>
用例2:
package main import (
"fmt"
"html/template"
"io"
"net/http"
) var myTemplate *template.Template type Result struct {
output string
} func (p *Result) Write(b []byte) (n int, err error) {
fmt.Println("called by template")
p.output += string(b)
return len(b), nil
} type Person struct {
Name string
Title string
Age int
} func userInfo(w http.ResponseWriter, r *http.Request) {
fmt.Println("handle hello")
//fmt.Fprintf(w,"hello")
var arr []Person
p := Person{Name: "Mary001", Age: , Title: "我的网站"}
p1 := Person{Name: "Mary002", Age: , Title: "我的个人网站"}
p2 := Person{Name: "Mary003", Age: , Title: "我的网站2"}
arr = append(arr, p)
arr = append(arr, p1)
arr = append(arr, p2) resultWriter := &Result{}
io.WriteString(resultWriter, "hello world")
err := myTemplate.Execute(w, arr)
if err != nil {
fmt.Println(err)
}
fmt.Println("template render data:", resultWriter.output)
//myTemplate.Execute(w, p)
//myTemplate.Execute(os.Stdout, p)
//file, err := os.OpenFile("C:/test.log", os.O_CREATE|os.O_WRONLY, 0755)
//if err != nil {
// fmt.Println("open failed err:", err)
// return
//}
}
func initTemplate(filename string) (err error) {
myTemplate, err = template.ParseFiles(filename)
if err != nil {
fmt.Println("parse file err:", err)
return
}
return
}
func main() {
initTemplate("d:/project/src/go_dev/day10/template_http/index.html")
http.HandleFunc("/user/info", userInfo)
err := http.ListenAndServe("127.0.0.1:8880", nil)
if err != nil {
fmt.Println("http listen failed")
}
}
template.go
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<p>hello world</p>
<table border="">
{{range .}}
<tr>
<td>{{.Name}}</td> <td>{{.Age}}</td><td>{{.Title}}</td>
</tr>
{{end}}
</table>
</body>
</html>
index.html