Yang's Blog

你好Golang

Golang是我学习编程以来接触的第二种编程语言,也是唯一的后端语言

你好Golang

1
2
3
4
5
6
7
package main
import "fmt"
func main(){
fmt.Printf("你好Golang,学习者Yang!!!")
}

输出如下:

1
你好Golang,学习者Yang!!!

通过http包来处理表单输入

Golang代码:

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
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"strings"
)
func sayHelloName(w http.ResponseWriter, r *http.Request) {
// 解析url传递的参数
r.ParseForm()
//在服务端打印信息
fmt.Println(r.Form)
fmt.Println("path", r.URL.Path)
fmt.Println("Scheme", r.URL.Scheme)
fmt.Println(r.Form["url_long"])
for k, v := range r.Form {
fmt.Println("key:", k)
// join() 方法用于把数组中的所有元素放入一个字符串。
// 元素是通过指定的分隔符进行分隔的
fmt.Println("val:", strings.Join(v, ""))
}
// 输出到客户端
fmt.Fprintf(w, "hello astaxie!")
}
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method)
if r.Method == "GET" {
t, _ := template.ParseFiles("login.html")
// 执行解析模板
// func (t *Template) Execute(wr io.Writer, data interface{}) error {
t.Execute(w, nil)
} else {
r.ParseForm()
fmt.Println("username:", r.Form["username"])
fmt.Println("password:", r.Form["password"])
}
}
func main() {
//设置访问路由
http.HandleFunc("/", sayHelloName)
http.HandleFunc("/login", login)
//设置监听端口
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal("ListenAndserve:", err)
}
}

HTML代码:

1
2
3
4
5
6
7
8
9
10
11
12
<html>
<head>
<title></title>
</head>
<body>
<form action="http://localhost:9090/login" method="post">
用户名:<input type="text" name="username">
密 码:<input type="text" name="password">
<input type="submit" value="登录">
</form>
</body>
</html>

通过上面代码我们知道获取请求方法是通过 r.Method 来完成的,我们可以访问 http://localhost:9090/ 来看看页面

Enjoy it ? Donate me ! 欣赏此文?求鼓励,求支持!