- 设置请求跳转
package main
import (
"io/ioutil"
"math/rand"
"net/http"
"strings"
)
func IndexHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate, no-store")
w.Header().Set("Content-Type", " text/html;charset=UTF-8")
w.Header().Set("Location", GetRandomPic("http://localhost:8181","/home/mzitu/"))//跳转地址设置
w.WriteHeader(307)
}
func main() {
http.HandleFunc("/", IndexHandler)
http.ListenAndServe(":8000", nil)
}
# 返回随机的一张图片地址
func GetRandomPic1(url string, pathName string) string {
rd, err := ioutil.ReadDir(pathName)
if err!= nil{
return "https://www.baidu.com"
}
var length = len(rd)
var fi = rd[rand.Intn(length)]
if fi.IsDir() {
return GetRandomPic(url, pathName + fi.Name() + "/")
}
return url + strings.Replace(pathName+fi.Name(),"/home/mzitu/","/", -1)
}
- 实现一个简单的web页面,点击图片可以更换一张随机图片,图片保存在/home/mzitu文件夹下。
项目文件结构:
----- js
index.js
----- view
index.html
main.go
main.go
package main
import (
"fmt"
"html/template"
"io/ioutil"
"math/rand"
"net/http"
"strings"
)
func welcome(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("view/index.html")
t.Execute(w, nil)
}
func RandomPic(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, GetRandomPic("http://localhost:8181","/home/mzitu/"))
}
func GetRandomPic(url string, pathName string) string {
rd, err := ioutil.ReadDir(pathName)
if err!= nil{
return "https://www.baidu.com"
}
var length = len(rd)
var fi = rd[rand.Intn(length)]
if fi.IsDir() {
return GetRandomPic(url, pathName + fi.Name() + "/")
}
return url + strings.Replace(pathName+fi.Name(),"/home/mzitu/","/", -1)
}
func main() {
server := http.Server{Addr: ":8090"}
http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("js"))))
http.HandleFunc("/", welcome)
http.HandleFunc("/randomPic", RandomPic)
server.ListenAndServe()
}
index.js
function myClick(){
let req;
if (window.XMLHttpRequest)
{
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
req=new XMLHttpRequest();
}
else
{
// IE6, IE5 浏览器执行代码
req=new ActiveXObject("Microsoft.XMLHTTP");
}
req.onreadystatechange=function()
{
if (req.readyState==4 && req.status==200)
{
document.getElementById("pic").src=req.responseText;
}
}
req.open("GET","/randomPic",false);
req.send();
}
document.ready(function (){
myClick();
})
index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>图片鉴赏</title>
<script type="text/javascript" src="/js/index.js"></script>
</head>
<body>
<img id="pic" src="" onclick="myClick()"/>
</body>
记录一下,自己爬妹子图写的玩玩的。
20211012