效果如下,通过ajax返回服务端的消息,顺便学习一下ajax了
模板用bootstrap和jQuery简单拼接了一下,两个我都不太会用
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<title>Go语言与ajax示例</title>
<!-- Bootstrap core CSS -->
<link href="assets/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container themed-container">
<header class="d-flex justify-content-center py-3">
<p class="h2">爬取页面信息</p>
</header>
<label class="form-label">网站地址</label>
<input class="form-control" id="url" name="url">
<div id="urlHelp" class="form-text">填写你要爬取的网页地址</div>
<label class="form-label">正则表达式</label>
<input class="form-control" id="reg" name="reg">
<div id="regHelp" class="form-text">正则表达式</div>
<div style="text-align:center">
<button id="btn1" type="submit" class="btn btn-primary">提交</button></div>
<p class="mt-4">爬取结果如下:</p>
<textarea class="form-control" id="txt1" rows="10"></textarea>
</div>
<script src="assets/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/dist/js/jquery-3.6.0.min.js"></script>
<script src="assets/dist/js/loli.js"></script>
</body>
</html>
js部分
$(function (){
$('#btn1').click(function (){
$.post('/ajax',{
url: $('#url').val(),
reg: $('#reg').val()
},function(data){
$('#txt1').text(data);
});
});
});
main.go
package main
import (
"io"
"log"
"net/http"
"regexp"
"text/template"
"github.com/fesiong/goproject/convert"
)
func getinfo(reg string, url string) [][]string { //爬虫结构体的getinfo方法
res, err := convert.Request(url, &convert.Options{})
if err != nil {
log.Fatal(err)
}
rep := regexp.MustCompile(reg) //匹配正则
match := rep.FindAllStringSubmatch(res.Body, -1) //返回的是[][]string,-1表示全部,1表示匹配1个,2就匹配2个
return match
}
func OnAjax(res http.ResponseWriter, req *http.Request) {
req.ParseForm()
info := getinfo(req.FormValue("reg"), req.FormValue("url"))
for _, m := range info {
io.WriteString(res, m[0]+"\n")
}
}
func index(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("index.html") //找模板
t.Execute(w, nil) //执行模板
}
func main() {
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
http.HandleFunc("/", index) //函数也是一种变量
http.HandleFunc("/ajax", OnAjax) //函数也是一种变量
http.ListenAndServe("localhost:8081", nil)
}