Ai
1 Star 0 Fork 0

叶明志/golang练习

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
main.go 4.23 KB
一键复制 编辑 原始数据 按行查看 历史
yemingzhi 提交于 2020-04-06 18:36 +08:00 . 简单修改
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())
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/yemingzhi/GolangLearnPractice1.git
git@gitee.com:yemingzhi/GolangLearnPractice1.git
yemingzhi
GolangLearnPractice1
golang练习
2bf136849dce

搜索帮助