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

相关推荐
用户0142260029841 分钟前
Go select详解
go
gfast1 分钟前
GFast开发MCP服务器之mark3labs/mcp-go库接入(一)
go
孔令飞8 分钟前
如何在 Go 中实现各种类型的链表?
人工智能·云原生·go
伊织code32 分钟前
PocketBase - 单文件开源后端解决方案
后端·开源·go·api·文件·pocketbase
考虑考虑11 小时前
go使用gorilla/websocket实现websocket
后端·程序员·go
GetcharZp16 小时前
xterm.js 终端神器到底有多强?用了才知道!
前端·后端·go
chxii16 小时前
2.2.1goweb内置的 HTTP 处理程序
go
纪元A梦17 小时前
华为OD机试真题——阿里巴巴找黄金宝箱Ⅰ(2025A卷:100分)Java/python/JavaScript/C/C++/GO最佳实现
java·c语言·javascript·c++·python·华为od·go
勤劳的牛马17 小时前
🚀 Go切片传参到底是值传递还是引用传递?
go
郝同学的测开笔记17 小时前
云原生探索系列(十七):Go 语言sync.Cond
后端·云原生·go