Last active
December 21, 2015 11:18
-
-
Save egdelwonk/6297604 to your computer and use it in GitHub Desktop.
a simple upload form in go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/http" | |
"text/template" | |
"io" | |
"io/ioutil" | |
) | |
var ( | |
templates = template.Must(template.ParseFiles( | |
"upload.html", | |
"view.html", | |
"error.html", | |
)) | |
) | |
func upload(w http.ResponseWriter, r *http.Request){ | |
if r.Method != "POST" { | |
templates.ExecuteTemplate(w, "upload.html", nil) | |
return | |
} | |
f, _, err := r.FormFile("image") | |
handleError(err) | |
defer f.Close() | |
t, err := ioutil.TempFile("media/uploads", "image-") | |
handleError(err) | |
defer t.Close() | |
_, err = io.Copy(t, f); | |
handleError(err) | |
http.Redirect(w, r, "/view?id="+ t.Name()[20:], 302) | |
} | |
func handleError (err error){ | |
if err != nil { | |
panic(err) | |
} | |
} | |
func view(w http.ResponseWriter, r *http.Request) { | |
templates.ExecuteTemplate(w, "view.html", r.FormValue("id")) | |
} | |
func errorHandler(fn http.HandlerFunc) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request){ | |
defer func(){ | |
if e := recover(); e != nil { | |
w.WriteHeader(500) | |
templates.ExecuteTemplate(w, "error.html", e) | |
} | |
}() | |
fn(w, r) | |
} | |
} | |
func main() { | |
http.HandleFunc("/", errorHandler(upload)) | |
http.HandleFunc("/view", errorHandler(view)) | |
http.HandleFunc("/media/", func(w http.ResponseWriter, r *http.Request) { | |
http.ServeFile(w, r, r.URL.Path[1:]) | |
fmt.Fprintf(w, r.URL.Path[1:]) | |
}) | |
http.ListenAndServe(":8080", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment