Just Do IT !

Golang语言学习从入门到实战----HTTP web开发编程

字数统计: 1.1k阅读时长: 6 min
2020/03/17 Share

1. HTTP编程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package main

import (
"fmt"
"net/http"
)

func main() {
http.HandleFunc("/", Hello)
http.HandleFunc("/usr/login", login)
http.HandleFunc("/usr/history", history)
err := http.ListenAndServe("0.0.0.0:8880", nil)
if err != nil {
fmt.Println("http listen failed")
}
}

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, "hello login !")
}

func history(w http.ResponseWriter, r *http.Request) {
fmt.Println("handle history")
_, _ = fmt.Fprintf(w, "hello history!")
}

打开浏览器访问本地的8880端口(因为我这里设置的是8880端口)
在
在这里插入图片描述
在这里插入图片描述

2. HTTP Client

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package demo2

import (
"fmt"
"io/ioutil"
"net/http"
)

func main() {
res, err := http.Get("https://www.baidu.com")
if err != nil {
fmt.Println("get err", err)
}

data, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("data err", err)
return
}
fmt.Println(string(data))

}

GET请求访问百度, 返回的网页信息
在这里插入图片描述

3. 表单处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main

import (
"io"
"net/http"
)

// 定义Html页面的显示表单
const form = `
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>产品添加-产品管理系统</title>
</head>
<body>
<h3>产品管理表单</h3>
<form action="#" method="post">
图书名称:<input type='text' name='title' />
<hr />
销售价格:<input type="text" name='price' />
<hr />
市场价格:<input type="text" name='market_price' />
<hr />
<input type="submit" name="submit" value="添加" />
<input type="reset" name="reset" value="重置" />
</form>
</body>
</html>
`

func formServer(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Type", "text/html")
switch request.Method {
case "GET": // 直接访问时为GET请求
_, _ = io.WriteString(writer, form)
case "POST": // 提交表单为POST请求
_ = request.ParseForm()
_, _ = io.WriteString(writer, "title = ")
_, _ = io.WriteString(writer, request.Form["title"][0]+"\n")
_, _ = io.WriteString(writer, "price = ")
_, _ = io.WriteString(writer, request.Form["price"][0]+"\n")
_, _ = io.WriteString(writer, "market_price = ")
_, _ = io.WriteString(writer, request.Form["market_price"][0]+"\n")
}
}

func simpleServer(writer http.ResponseWriter, request *http.Request) {
_, _ = io.WriteString(writer, "<h1>Hello ! This is test1")
}
func main() {
http.HandleFunc("/test1", simpleServer) // localhost:8880/test1 访问simpleServer定义的页面
http.HandleFunc("/test2", formServer) // localhost:8880/test2 访问formServer定义的页面
if err := http.ListenAndServe("0.0.0.0:8880", nil); err != nil {

}
}

http://localhost:8880/test1 可以访问到设置的test1页面
在这里插入图片描述
http://localhost:8880/test2 可以访问到设置的test2页面
在这里插入图片描述
提交表单会返回输入的值
在这里插入图片描述

4. 捕获Panic错误处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main

import (
"io"
"log"
"net/http"
)

// 定义Html页面的显示表单
const form = `
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>产品添加-产品管理系统</title>
</head>
<body>
<h3>产品管理表单</h3>
<form action="#" method="post">
图书名称:<input type='text' name='title' />
<hr />
销售价格:<input type="text" name='price' />
<hr />
市场价格:<input type="text" name='market_price' />
<hr />
<input type="submit" name="submit" value="添加" />
<input type="reset" name="reset" value="重置" />
</form>
</body>
</html>
`

func formServer(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Type", "text/html")
switch request.Method {
case "GET": // 直接访问时为GET请求
_, _ = io.WriteString(writer, form)
case "POST": // 提交表单为POST请求
_ = request.ParseForm()
_, _ = io.WriteString(writer, "title = ")
_, _ = io.WriteString(writer, request.Form["title"][0]+"\n")
_, _ = io.WriteString(writer, "price = ")
_, _ = io.WriteString(writer, request.Form["price"][0]+"\n")
_, _ = io.WriteString(writer, "market_price = ")
_, _ = io.WriteString(writer, request.Form["market_price"][0]+"\n")
}
}

func simpleServer(writer http.ResponseWriter, request *http.Request) {
_, _ = io.WriteString(writer, "<h1>Hello ! This is test1")
panic("This is a panic test !")
}
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)) // localhost:8880/test1 访问simpleServer定义的页面
http.HandleFunc("/test2", logPanics(formServer)) // localhost:8880/test2 访问formServer定义的页面
if err := http.ListenAndServe("0.0.0.0:8880", nil); err != nil {

}
}

Demo添加了panic处理函数logPanics, 可以在终端查看捕获的Panic信息
在这里插入图片描述

5. 调用模板网页

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import (
"fmt"
"html/template"
"os"
)

type Person struct {
Name string
Age string
}

func main() {
t, err := template.ParseFiles("E:/Go/Golang_Studycode/src/demoCode/domo5/index.html") // index.html路径
if err != nil {
fmt.Println(" Parse file err:", err)
return
}
p := Person{Name:"Jack", Age:"20"}
if err := t.Execute(os.Stdout, p); err != nil{
fmt.Println("There was an erros:",err.Error())
}
}

index.php

1
2
3
4
5
6
7
8
9
10
<html>
<head>
<title>This is a test</title>
</head>
<body>
<p> this is a test!</p>
<p> Hello {{.Name}} , you age is {{.Age}}</p>

</body>
</html>

在这里插入图片描述

CATALOG
  1. 1. 1. HTTP编程
  2. 2. 2. HTTP Client
  3. 3. 3. 表单处理
  4. 4. 4. 捕获Panic错误处理
  5. 5. 5. 调用模板网页