在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
工具: LiteIDE 配置:
代码:list.html <!doctype html> <html> <head> <meta charset="utf-8"> <title>List</title> </head> <body> <ol> {{range $.images}} <li><a href="/view?id={{.|urlquery}}">{{.|html}}</a></li> {{end}} </ol> </body> </html>
upload.html <!doctype html> <html> <head> <meta charset="utf-8"> <title>Upload</title> </head> <body> <form method="POST" action="/upload" enctype="multipart/form-data"> Choose an image to upload: <input name="image" type="file" /> <input type="submit" value="Upload" /> </form> </body> </html>
photoweb.go: // photoweb package main import ( "fmt" "html/template" "io" "io/ioutil" "log" "net/http" "os" "path" "runtime/debug" "strings" ) const ( ListDir = 0x0001 TEMPLATE_DIR = "./view" UPLOAD_DIR = "./uploads" ) var templates map[string]*template.Template = make(map[string]*template.Template) func init() { fileInfoArr, err := ioutil.ReadDir(TEMPLATE_DIR) check(err) var templateName, templatePath string for _, fileInfo := range fileInfoArr { templateName = fileInfo.Name() var ext string if ext = path.Ext(templateName); ext != ".html" { continue } templatePath = TEMPLATE_DIR + "/" + templateName log.Println("Loading template:", templatePath) t := template.Must(template.ParseFiles(templatePath)) tmpl := strings.TrimSuffix(templateName, ext) templates[tmpl] = t } } 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", e) // logging log.Println("WARN: panic in %v - %v", fn, err) log.Println(string(debug.Stack())) } }() fn(w, r) } } func check(err error) { if err != nil { panic(err) } } func renderHtml(w http.ResponseWriter, tmpl string, locals map[string]interface{}) { err := templates[tmpl].Execute(w, locals) check(err) } func uploadHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { //io.WriteString(w, "<form method='POST' action='/upload' enctype='multipart/form-data'> Choose an image to upload: <input name='image' type='file'/> <input type='submit' value='Upload'/> </form>") // t, err := template.ParseFiles("upload.html") // if err != nil { // http.Error(w, err.Error(), http.StatusInternalServerError) // return // } // t.Execute(w, nil) // return renderHtml(w, "upload", nil) } if r.Method == "POST" { f, h, err := r.FormFile("image") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } filename := h.Filename defer f.Close() t, err := os.Create(UPLOAD_DIR + "/" + filename) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer t.Close() if _, err := io.Copy(t, f); 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 := UPLOAD_DIR + "/" + imageId 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) fileInfoArr, err := ioutil.ReadDir("./uploads") check(err) locals := make(map[string]interface{}) images := []string{} for _, fileInfo := range fileInfoArr { images = append(images, fileInfo.Name()) } locals["images"] = images renderHtml(w, "list", locals) } 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() { fmt.Println("Hello World!") mux := http.NewServeMux() staticDirHandler(mux, "/assets/", "./public", 0) mux.HandleFunc("/", safeHandler(listHandler)) mux.HandleFunc("/view", safeHandler(viewHandler)) mux.HandleFunc("/upload", safeHandler(uploadHandler)) err := http.ListenAndServe(":8080", mux) if err != nil { log.Fatal("ListenAndServe: ", err.Error()) } }
测试:
参考:《GO 语言编程》
|
请发表评论