finnally doooo and close #11
Former-commit-id: b899f43722862ed4aafbca659670f26011ae727d [formerly 746709cdc2fa58bc69a71fa795a5589a1145d853] [formerly 5aab2327e90c4dd0a47b71d8ef90043e8918db06 [formerly eb22fd20ce78b48c6a2a3c3ffc59b1ca76feda5e]] Former-commit-id: ca8b01af19ef3bbd870636170f60fd7ae8e4cd7f [formerly be235a498e36298e07f1b5d07939668d57e08fe2] Former-commit-id: 6bccf20702c8b3867a3a2ebae711834a740a06ad
This commit is contained in:
54
handlers/checksum.go
Normal file
54
handlers/checksum.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"crypto/sha1"
|
||||
"crypto/sha256"
|
||||
"crypto/sha512"
|
||||
"encoding/hex"
|
||||
e "errors"
|
||||
"hash"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/hacdias/caddy-filemanager/config"
|
||||
"github.com/hacdias/caddy-filemanager/file"
|
||||
"github.com/hacdias/caddy-filemanager/utils/errors"
|
||||
)
|
||||
|
||||
// Checksum calculates the hash of a file. Supports MD5, SHA1, SHA256 and SHA512.
|
||||
func Checksum(w http.ResponseWriter, r *http.Request, c *config.Config, i *file.Info) (int, error) {
|
||||
query := r.URL.Query().Get("checksum")
|
||||
|
||||
file, err := os.Open(i.Path)
|
||||
if err != nil {
|
||||
return errors.ErrorToHTTPCode(err, true), err
|
||||
}
|
||||
|
||||
defer file.Close()
|
||||
|
||||
var h hash.Hash
|
||||
|
||||
switch query {
|
||||
case "md5":
|
||||
h = md5.New()
|
||||
case "sha1":
|
||||
h = sha1.New()
|
||||
case "sha256":
|
||||
h = sha256.New()
|
||||
case "sha512":
|
||||
h = sha512.New()
|
||||
default:
|
||||
return http.StatusBadRequest, e.New("Unknown HASH type")
|
||||
}
|
||||
|
||||
_, err = io.Copy(h, file)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
val := hex.EncodeToString(h.Sum(nil))
|
||||
w.Write([]byte(val))
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
Reference in New Issue
Block a user