我是靠谱客的博主 明理服饰,最近开发中收集的这篇文章主要介绍golang解析html网页的方法,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

1.先看一下整个结构:

主要是web和html目录,分别存放go代码和html相关的资源文件。

2.html代码比较简单,代码如下:

<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代码也比较简单,如下:

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网页的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持靠谱客。

最后

以上就是明理服饰为你收集整理的golang解析html网页的方法的全部内容,希望文章能够帮你解决golang解析html网页的方法所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(124)

评论列表共有 0 条评论

立即
投稿
返回
顶部