最近再看Go语言web编程,使用net/http模块编写了一个简单的登录验证和文件上传的功能,在此做个简单记录。
目录
1.文件目录结构
2.编译运行
3.用户登录
4.文件上传
代码如下:
package mainimport ("fmt""html/template""io""log""net/http""os"
)/*
go运行方式:
(1)解释运行
go run main.go(2)编译运行
--使用默认名
go build main.go
./main
--指定可执行程序名
go build -o test main.go
./test
*/// http://127.0.0.1:8181/login
func login(w http.ResponseWriter, r *http.Request) {fmt.Println("method", r.Method)if r.Method == "GET" {t, _ := template.ParseFiles("login.html")t.Execute(w, nil)} else {r.ParseForm()fmt.Println("username", r.Form["username"])fmt.Println("password", r.Form["password"])fmt.Fprintf(w, "登录成功")}
}// http://127.0.0.1:8181/upload
func upload(writer http.ResponseWriter, r *http.Request) {r.ParseMultipartForm(32 << 10)file, handler, err := r.FormFile("uploadfile")if err != nil {fmt.Fprintf(writer, "上传出错")fmt.Println(err)return}defer file.Close()fmt.Println("handler.Filename", handler.Filename)f, err := os.OpenFile("./filedir/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)if err != nil {fmt.Println(err)fmt.Fprintf(writer, "上传出错")return}defer f.Close()io.Copy(f, file)fmt.Fprintf(writer, "上传成功")
}func common_handle() {http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {w.Write([]byte("Hello world !"))})http.HandleFunc("/login", login)http.HandleFunc("/upload", upload)
}func main1() {common_handle()//监听8181端口err := http.ListenAndServe(":8181", nil)if err != nil {log.Fatal("err:", err)}
}// 声明helloHandler
type helloHandler struct{}// 定义helloHandler
func (m *helloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {w.Write([]byte("Hello world, this is my first golang programe !"))
}func welcome(w http.ResponseWriter, r *http.Request) {w.Write([]byte("Welcome to golang family !"))
}func main2() {a := helloHandler{}//使用http.Handlehttp.Handle("/hello", &a)http.Handle("/welcome", http.HandlerFunc(welcome))common_handle()server := http.Server{Addr: "127.0.0.1:8181",Handler: nil, // 对应DefaultServeMux路由}server.ListenAndServe()
}func main() {main2()
}
login.html
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"/><title>欢迎进入首页</title></head><body><h3>登录测试</h3><hr/><form action="http://localhost:8181/login" method="post"><table border=0 title="测试"><tr><td>用户名:</td><td><input type="text" name="username"></td></tr><tr><td>密码:</td><td><input type="password" name="password"></td></tr><tr><td colspan=2><input type="reset" /><input type="submit" value="登录" /></td></tr></table></form><br><h3>文件上传测试</h3><hr/><form action="http://localhost:8181/upload" method="post" enctype="multipart/form-data"><input type="file" name="uploadfile"/><input type="submit" value="upload"></form></body>
</html>
1.文件目录结构
2.编译运行
3.用户登录
http://127.0.0.1:8181/login
4.文件上传