源码
package main
import "net/http"
import "html/template"
var uploadTemplate = template.MustParseFile("upload.html", nil)
//var uploadTemplate = template.Must(template.ParseFiles("upload.html", nil))
func check(err os.Error) {
if err != nil {
panic(err)
}
}
func upload(w http.ResponseWriter, r *http.Request) {
uploadTemplate.Execute(w, nil)
if r.Method != "POST" {
uploadTemplate.Execute(w, nil)
return
}
f, _, err := r.FormFile("image")
// if err != nil {
// http.Error(w, err.String(), 500)
// return
// }
check(err)
defer f.Close()
t, err := ioutil.TempFile(".", "image-")
// if err != nil {
// http.Error(w, err.String(), 500)
// return
// }
check(err)
defer t.Close()
_1, err := io.Copy(t, f)
// if _, err := io.Copy(t, f); err != nil {
// http.Error(w, err.String(), 500)
// return
// }
check(err)
http.Redirect(w, r, "/view?id="+t.Name()[6:], 302)
}
//var errorTemplate = template.MustParseFile("error.html", nil)
var uploadTemplate = template.Must(template.ParseFiles("error.html"))
func errorHandler(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer func() {
if e, ok := recover().(os.Error); ok {
w.WriteHeader(500)
errorTemplate.Execute(w, e)
}
}()
fn(w, r)
}
}
func view(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image")
http.ServeFile(w, r, "image-"+r.FormValue("id"))
}
func main() {
http.HandleFunc("/", upload)
http.HandleFunc("/", errorHandler(upload))
http.HandleFunc("/view", errorHandler(view))
http.ListenAndServe(":8080", nil)
}
报错
./upload.go:6: undefined: "html/template".MustParseFile
./upload.go:10: undefined: os in os.Error
./upload.go:31: undefined: ioutil in ioutil.TempFile
./upload.go:39: undefined: io in io.Copy
./upload.go:49: uploadTemplate redeclared in this block
previous declaration at ./upload.go:6
./upload.go:54: undefined: os in os.Error
./upload.go:56: undefined: errorTemplate in errorTemplate.Execute
有疑问加站长微信联系(非本文作者)