1.先看一下整個結構:
主要是web和html目錄,分別存放go代碼和html相關的資源文件。
2.html代碼比較簡單,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<html> <head> <title>Go web</title> </head> <body> <img src= "/html/pics/girl.jpg" width= "500" height= "500" > <form action= "http://127.0.0.1:8080/login" method= "post" > 用戶名:<input type= "text" name= "username" > 密碼:<input type= "password" name= "password" > <input type= "submit" value= "登陸" > </form> </body> </html> |
就是顯示一張圖片,然后加登陸表單。
3.而go代碼也比較簡單,如下:
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
|
package main import ( "fmt" "html/template" "log" "net/http" ) func login(w http.ResponseWriter, r *http.Request) { r.ParseForm() if r.Method == "GET" { t, err := template.ParseFiles( "html/login.html" ) if err != nil { fmt.Fprintf(w, "parse template error: %s" , err.Error()) return } t.Execute(w, nil) } else { username := r.Form[ "username" ] password := r.Form[ "password" ] fmt.Fprintf(w, "username = %s, password = %s" , username, password) } } func main() { http.HandleFunc( "/html/pics/" , func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, r.URL.Path[1:]) }) http.HandleFunc( "/login" , login) err := http.ListenAndServe( ":8080" , nil) if err != nil { log.Fatal( "ListenAndServe: " , err) } } |
主要是注意顯示圖片的路徑,不能是原來的html的路徑,必須是go認識的路徑,所以圖片的位置也設置了路由,見http.ServeFile方法,并注意html設置的圖片路徑。
以上這篇golang解析html網頁的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/rambo_huang/article/details/69218252