Go语言学习笔记(1)
Go语言学习笔记
由于目前是学生身份,所以使用的是JetBrains全家桶系列,Goland
这是多处理器多Handler方式
package main
import (
"fmt"
"net/http"
"strings"
)
//多处理器多Handler
type MyHandler struct {
}
func(m *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request){
w.Write([]byte("return data handler1"))
}
type MyHandle struct{
}
func(m *MyHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("return data handler2"))
}
func main(){
h:=MyHandler{}
h2:=MyHandle{}
server := http.Server{Addr: "localhost:8090"}
http.Handle("/first",&h)
http.Handle("/second",&h2)
server.ListenAndServe()
}
这是多处理函数方式
//多处理函数方式
func first(w http.ResponseWriter,r *http.Request){
fmt.Fprintln(w,"多函数func first")
}
func second(w http.ResponseWriter,r *http.Request){
fmt.Fprintln(w,"多函数func second")
}
func main(){
server:=http.Server{Addr:"localhost:8090"}
http.HandleFunc("/first",first)
http.HandleFunc("/second",second)
server.ListenAndServe()
}
这部分是helloworld级别的代码
//HelloWorld demo
func sayhelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //解析url传递的参数,对于POST则解析响应包的主体(request body)
//注意:如果没有调用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)
fmt.Println("val:", strings.Join(v, ""))
}
fmt.Fprintf(w, "Hello astaxie!") //这个写入到w的是输出到客户端的
}
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) //获取请求的方法
if r.Method == "GET" {
t, _ := template.ParseFiles("login.gtpl")
log.Println(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)
}
}
其中login的html页面放在src文件下,即目前和working directory平行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/login" method="post">
用户名:<input type="text" name="username">
密码:<input type="password" name="password">
<input type="submit" value="登陆">
</form>
</body>
</html>
以下这部分是获取请求头和请求获取参数的代码
func param(w http.ResponseWriter, r *http.Request){
h:=r.Header
fmt.Fprintln(w,h)
fmt.Fprintln(w,h["Accept-Encoding"])
fmt.Fprintln(w,len(h["Accept-Encoding"]))
for _,n:=range strings.Split(h["Accept-Encoding"][0],","){
fmt.Fprintln(w,strings.TrimSpace(n))
}
r.ParseForm()
fmt.Fprintln(w,r.Form)
fmt.Fprintln(w,r.FormValue("name"))
}
func main(){
server:=http.Server{Addr:":8090"}
http.HandleFunc("/param",param)
server.ListenAndServe()
}