Skip to content

Instantly share code, notes, and snippets.

@mattn
Last active August 3, 2021 05:26
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattn/5394240 to your computer and use it in GitHub Desktop.
Save mattn/5394240 to your computer and use it in GitHub Desktop.
package main
import (
"crypto/sha1"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
const indexPage = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="/" method="POST" enctype="multipart/form-data">
<input type="file" name="image1">
<input type="submit">
</form>
</body>
</html>
`
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
if r.URL.Path == "/" {
fmt.Fprintf(w, indexPage)
} else {
if f, e := filepath.Abs(r.URL.Path); e == nil {
http.ServeFile(w, r, f)
} else {
http.Error(w, e.Error(), http.StatusNotFound)
}
}
} else {
var e error
var f io.Writer
var m multipart.File
var hex string
if m, _, e = r.FormFile("image1"); e == nil {
sha1h := sha1.New()
if _, e = io.Copy(sha1h, m); e == nil {
m.Seek(0, os.SEEK_SET)
hex = fmt.Sprintf("%x", sha1h.Sum(nil))
if f, e = os.Create(hex + ".png"); e == nil {
_, e = io.Copy(f, m)
}
}
}
if e == nil {
http.Redirect(w, r, hex+".png", 302)
} else {
http.Error(w, e.Error(), http.StatusInternalServerError)
}
}
})
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment