Go语言学习笔记
由于目前是学生身份,所以使用的是JetBrains全家桶系列,Goland
这是多处理器多Handler方式
package main
import (
"fmt"
"net/http"
"strings"
)
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级别的代码
func sayhelloName(w http.ResponseWriter, r *http.Request) {
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)
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.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()
}
|
请发表评论