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.根据文件头判断文件类型进行不同处理没有实现

相关推荐
liangbm33 小时前
AI-ViewNote:把网课和会议视频自动卷成结构化笔记
ai·typescript·go·软件构建·开源软件·react·桌面软件
我叫黑大帅5 小时前
Gin 实战入门:从环境搭建到企业级常用特性全解析
后端·面试·go
我叫黑大帅5 小时前
Gin 日志体系详解
后端·面试·go
F1FJJ6 小时前
Shield CLI v0.3.3 新增 PostgreSQL 插件:浏览器里管理 PG 数据库
网络·网络协议·docker·postgresql·容器·go
mCell13 小时前
【万字长文】从 AI SDK 到 mini-opencode:一次很巧的 Go Agent 架构实践
架构·go·agent
jump_jump16 小时前
深入理解 Go Context:从原理到实战(基于 Go 1.26)
go·源码
哈里谢顿18 小时前
golang目前遇到的面试题
go
哈里谢顿18 小时前
python与golang性能差异对比
go
前端Hardy2 天前
Wails v3 正式发布:用 Go 写桌面应用,体积仅 12MB,性能飙升 40%!
前端·javascript·go
golang学习记2 天前
Go 语言生产环境必备包清单
go