Go图片列表

需求

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

代码

Go 复制代码
package main

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

func handleRequest(w http.ResponseWriter, r *http.Request) {
	fmt.Println(r.Proto + " " + r.Host + " " +r.RequestURI)
	dir, err := ioutil.ReadDir("." + r.RequestURI)
	
	//排序
	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, "." + r.RequestURI);		
	} else {
		path := "/"
		if (r.RequestURI != "/") {
			n := strings.LastIndex(r.RequestURI, "/");
			if (n != 0) {
				path = string(r.RequestURI[: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"				
				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);
}

问题

1.不支持非英文目录

2.删除目录没有实现

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

相关推荐
资源开发与学习20 小时前
Go工程师进阶 IM系统架构设计与落地
go
源码7可20 小时前
GO进阶,IM系统架构设计与落地 教程分享
go
Mgx1 天前
Go语言实现的简易远程传屏工具:让你的屏幕「飞」起来
go
Mgx1 天前
布隆过滤器(go):一个可能犯错但从不撒谎的内存大师
go
Lea__1 天前
深拷贝优化:从 copier 到 go_deep_copy 的演进
go
喵个咪2 天前
开箱即用的GO后台管理系统 Kratos Admin - 站内信
后端·微服务·go
Mgx2 天前
用 Go 手搓一个 NTP 服务:从“时间混乱“到“精准同步“的奇幻之旅
go
wohuidaquan2 天前
本地生活曝光缺失?GEO语义锚点来救场
go
代码扳手2 天前
Golang + Genkit 实战:告别手动周报,让 AI 帮你整理一切!
go·ai编程
砖业林coco2 天前
go语言使用 zhinao-go 轻松调用 360智脑
llm·go