Go語言實現簡單的登入和檔案上傳
阿新 • • 發佈:2021-11-28
最近學習Go Web程式設計,先學了個基礎的登入和檔案上傳,使用的是Go語言自帶的net/http包
Go語言處理請求非常簡單,呼叫http.ListenAndServe函式,監聽對應埠,然後http.HandleFunc函式根據請求路徑呼叫不同函式
主函式如下
func main() { http.HandleFunc("/",handleRequest) http.HandleFunc("/login",login) http.HandleFunc("/upload",upload) //監聽8080埠 err:=http.ListenAndServe(":8080",nil) if err!=nil{ log.Fatal("err:",err) } }
先po上咱用的html檔案:login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="http://localhost:8080/login" method="post"> <input type="text" name="username"> <input type="password" name="password"> <input type="submit" value="登入"> </form> <br> 上傳檔案 <form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data"> <input type="file" name="uploadfile"/> <input type="submit" value="upload"> </form> </body> </html>
先看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,"登入成功") } }
拿到請求r後,判斷是什麼請求方法,如果是get方法,返回login.html檔案
如果是post方法,代表這是進行登入操作了,然後使用ParesForm()方法,這個方法會解析出r.Form和r.PoatForm,不先呼叫這個方法,是獲取不到表單中的值的
r.Form底層是一個map,所以可以用表單中的name來獲取value
控制檯輸出
這裡的123d都是我亂打進去的
再看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()
f,err:=os.OpenFile("./test"+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,"上傳成功")
}
ParseMultipartForm()這個函式是解析上傳來的檔案的,引數交maxMemory,檔案小與等於maxMemory的部分存在記憶體中,多出的部分存在系統的臨時檔案中。它在必要情況下,會呼叫一下ParseForm(),解析請求提
FormFile返回我們一個檔案File型別的物件,就是上傳的檔案,handler是裡面是檔案的一些資訊
os.OpenFile函式開啟一個我們將寫入的檔案,os.O_WRONLY|os.O_CREATE代表的是開啟模式,以只寫模式開啟,並且檔案不存在就建立一個,0666代表的是檔案模式,有讀寫許可權
然後就沒什麼難懂的了。
看我演示
選擇一個圖片
點選上傳,成功了
看目錄裡面已經有了這個圖片