代码拉取完成,页面将自动刷新
package main
import (
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"runtime/debug"
"strings"
)
const (
//上传文件的位置
uploadDir = "./uploads"
//模板文件的位置
templateDir = "./views"
//
listDir = 0x0001
)
//设置模板缓存,用的时候直接解析即可
var templates map[string]*template.Template = make(map[string]*template.Template)
func init() {
//读取模板文件,设置模板缓存
fileInfoArr, err := ioutil.ReadDir(templateDir)
if err != nil {
panic(err)
return
}
var templateName, templatePath string
for _, fileInfo := range fileInfoArr {
templateName = fileInfo.Name()
if ext := path.Ext(templateName); ext != ".html" {
continue
}
templatePath = templateDir + "/" + templateName
log.Println("Loading template:", templatePath)
t := template.Must(template.ParseFiles(templatePath))
//去除文件后面的".html"
tmpl := strings.ReplaceAll(templateName, ".html", "")
//把模板解析的缓存放到map里,用的时候直接就找到了
templates[tmpl] = t
}
}
func renderHTML(w http.ResponseWriter, tmpl string, locals map[string]interface{}) (err error) {
err = templates[tmpl].Execute(w, locals)
return err
}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
if err := renderHTML(w, "upload", nil); err != nil {
http.Error(w, err.Error(),
http.StatusInternalServerError)
return
}
}
if r.Method == "POST" {
file, fileheader, err := r.FormFile("image")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
filename := fileheader.Filename
defer file.Close()
serverFile, err := os.Create(uploadDir + "/" + filename)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer serverFile.Close()
if _, err := io.Copy(serverFile, file); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/view?id="+filename, http.StatusFound)
}
}
func viewHandler(w http.ResponseWriter, r *http.Request) {
imageID := r.FormValue("id")
imagePath := uploadDir + "/" + imageID
if exists := isExists(imagePath); !exists {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "image")
http.ServeFile(w, r, imagePath)
}
func isExists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
return os.IsExist(err)
}
func listHandler(w http.ResponseWriter, r *http.Request) {
fileInfoArr, err := ioutil.ReadDir("./uploads")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
locals := make(map[string]interface{})
images := []string{}
for _, fileInfo := range fileInfoArr {
images = append(images, fileInfo.Name())
}
locals["images"] = images
// t, err := template.ParseFiles("list.html")
// if err != nil {
// http.Error(w, err.Error(),
// http.StatusInternalServerError)
// return
// }
// t.Execute(w, locals)
if err = renderHTML(w, "list", locals); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func safeHandler(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err, ok := recover().(error); ok {
http.Error(w, err.Error(), http.StatusInternalServerError)
// 或者输出自定义的 50x 错误页面
// w.WriteHeader(http.StatusInternalServerError)
// renderHtml(w, "error", err)
// logging
log.Println("WARN: panic in %v - %v", fn, err)
log.Println(string(debug.Stack()))
}
}()
fn(w, r)
}
}
func staticDirHandler(mux *http.ServeMux, prefix string, staticDir string, flags int) {
mux.HandleFunc(prefix, func(w http.ResponseWriter, r *http.Request) {
file := staticDir + r.URL.Path[len(prefix)-1:]
if (flags & listDir) == 0 {
if exists := isExists(file); !exists {
http.NotFound(w, r)
return
}
}
http.ServeFile(w, r, file)
})
}
func main() {
mux := http.NewServeMux()
staticDirHandler(mux, "/files/", "./public", 0)
mux.HandleFunc("/list", safeHandler(listHandler))
mux.HandleFunc("/view", safeHandler(viewHandler))
mux.HandleFunc("/", safeHandler(uploadHandler))
err := http.ListenAndServe(":8080", mux)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。