Skip to content

Instantly share code, notes, and snippets.

@optman
Last active October 19, 2016 06:52
Show Gist options
  • Save optman/07d15c20312446aa17dffcb6af40145e to your computer and use it in GitHub Desktop.
Save optman/07d15c20312446aa17dffcb6af40145e to your computer and use it in GitHub Desktop.
simple pic host
package main
import (
"flag"
"fmt"
"html"
"io"
"log"
"net/http"
"os"
"path"
"text/template"
)
var listen_addr = flag.String("listen_addr", ":80", "listen address")
var max_size_kb = flag.Int("max_size", 1024, "max size(KB)")
var save_path = flag.String("path", "img", "image storage path)")
const static_path = "/images/"
func main() {
flag.Parse()
http.HandleFunc("/", root)
http.HandleFunc("/upload", upload)
http.HandleFunc(static_path, show)
err := http.ListenAndServe(*listen_addr, nil)
if err != nil {
log.Fatal(err)
}
}
func root(w http.ResponseWriter, r *http.Request) {
html := `<form enctype="multipart/form-data" action="upload" method="POST">
Choose a file to upload(&lt;{{.max_size_kb}}KB): <br />
<input type="hidden" name="MAX_FILE_SIZE" value="{{.max_size}}" />
<input name="file" type="file" /> <input type="submit" value="Upload File" />
</form>`
t, _ := template.New("foo").Parse(html)
w.Header().Set("content-Type", "text/html")
data := make(map[string]interface{})
data["max_size_kb"] = *max_size_kb
data["max_size"] = *max_size_kb * 1024
t.Execute(w, data)
}
func upload(w http.ResponseWriter, r *http.Request) {
file, fileHeader, err := r.FormFile("file")
if err != nil {
fmt.Fprintf(w, "%s", err)
return
}
file_name := html.EscapeString(fileHeader.Filename)
full_path := path.Join(*save_path, file_name)
if _, err = os.Stat(full_path); err == nil {
fmt.Fprintf(w, "same file name exist!")
return
}
of, err := os.Create(full_path)
if err != nil {
fmt.Fprintf(w, "%s", err)
return
}
defer of.Close()
_, err = io.Copy(of, file)
if err != nil {
fmt.Fprintf(w, "%s", err)
return
}
http.Redirect(w, r, path.Join(static_path, file_name), 302)
}
func show(w http.ResponseWriter, r *http.Request) {
full_path := path.Join(*save_path, html.EscapeString(path.Base(r.URL.Path)))
f, err := os.Open(full_path)
if err != nil {
fmt.Println(err)
http.NotFound(w, r)
return
}
defer f.Close()
//w.Header().Set("content-Type", "image/jpeg")
io.Copy(w, f)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment