Go图片列表

需求

在一个页面浏览目录下所有图片

代码

package main

import (
	"net/http"
	"fmt"
	"io/ioutil"
	"sort"
	"strings"
	"strconv"
    "net/url"
)

func handleRequest(w http.ResponseWriter, r *http.Request) {	
    decodedUrl, err := url.QueryUnescape(r.RequestURI)
    fmt.Println(r.Proto + " " + r.Host + " " + decodedUrl)    
	//dir, err := ioutil.ReadDir("." + r.RequestURI)
    dirr := "../../pic" //本地根目录:上级/上级/pic
    dir, err := ioutil.ReadDir(dirr + decodedUrl)
	
	//排序
	sort.Slice(dir, func(i, j int) bool {
		di := dir[i]
        dj := dir[j]
        if di.IsDir() && !dj.IsDir() { // 目录在前
            return true
        } else if !di.IsDir() && dj.IsDir() { // 目录在后
            return false
        }
        //return dir[i].Name() < dir[j].Name() //和WIN7不一样
		return dir[i].ModTime().Before(dir[j].ModTime())
    })
	
	if err != nil {
		//http.ServeFile(w, r, "." + decodedUrl);
        http.ServeFile(w, r, dirr + decodedUrl);
	} else {
		path := "/"
		if (decodedUrl != "/") {
			n := strings.LastIndex(decodedUrl, "/");
			if (n != 0) {
				path = string(decodedUrl[:n])
			}
		}
		ddir := ""
		if (r.RequestURI != "/") {
			ddir = " <a href=''>删除此目录</a>"
		}
		str := "<html>\n<head>\n<title>文件列表</title>\n</head>\n<style>\na, img { -webkit-user-drag:none; }\na { text-decoration:none; padding:10px; margin:10px; background:lightgray; display:inline-block; }\na:hover { background:gray; }\nimg { max-width: 100%; }\n</style>\n<body>\n<p><a href='" + path + "'>[" + path + "]</a>" + ddir + "</p>"
        path = "/"
		if (r.RequestURI != "/") {
			path = r.RequestURI + "/"
		}
		var count_dir, count_file int
		for _, file := range dir {
			if (file.IsDir()) {				
				str += "<a href='" + path + file.Name() + "'>" + file.Name() + "</a>\n"
				count_dir++
			} else {			
				str += "<img src='" + path + file.Name() +"'>\n"
				//str += "<video src='" + r.RequestURI + "/" + file.Name() + "' controls='controls'></video>\n"
				count_file++
			}
		}	
		str += "<p>目录" + strconv.Itoa(count_dir) + "个,文件" + strconv.Itoa(count_file) + "个</p>\n</body>\n</html>"
		w.Write([]byte(str))
	}
}

func main() {	
	fmt.Println("http://localhost:8000");
	http.HandleFunc("/", handleRequest);
	http.ListenAndServe(":8000", nil);
}

注意

不支持中文目录用 url.QueryUnescape() 解决了。

问题

1.删除目录没有实现

2.根据文件头判断文件类型进行不同处理没有实现

3.根目录只支持相对路径

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值