add new imageHandler
This commit is contained in:
parent
08814b0e82
commit
123433d156
2 changed files with 46 additions and 1 deletions
35
go/main.go
35
go/main.go
|
@ -21,6 +21,7 @@ var (
|
|||
func main() {
|
||||
http.HandleFunc("/", homeHandler)
|
||||
http.HandleFunc("/upload", uploadHandler)
|
||||
http.HandleFunc("/image/", imageHandler)
|
||||
http.HandleFunc("/view/", viewHandler)
|
||||
|
||||
fmt.Println("Server listening on :8080")
|
||||
|
@ -153,7 +154,7 @@ func uploadHandler(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
}
|
||||
|
||||
func viewHandler(w http.ResponseWriter, r *http.Request) {
|
||||
func imageHandler(w http.ResponseWriter, r *http.Request) {
|
||||
filePath := r.URL.Path[len("/view/"):]
|
||||
imagePath := "./uploads/" + filePath
|
||||
|
||||
|
@ -173,3 +174,35 @@ func viewHandler(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
}
|
||||
}
|
||||
|
||||
func viewHandler(w http.ResponseWriter, r *http.Request) {
|
||||
filePath := r.URL.Path[len("/view/"):]
|
||||
imagePath := "./uploads/" + filePath
|
||||
|
||||
// Überprüfen, ob die Bilddatei existiert
|
||||
if _, err := os.Stat(imagePath); os.IsNotExist(err) {
|
||||
http.Error(w, "Bild nicht gefunden", http.StatusNotFound)
|
||||
log.Printf("Bild nicht gefunden: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Verwenden von html/template zur sicheren Ausgabe von HTML
|
||||
tmpl, err := template.ParseFiles("templates/viewImage.html")
|
||||
if err != nil {
|
||||
http.Error(w, "Fehler beim Laden des Templates", http.StatusInternalServerError)
|
||||
log.Printf("Fehler beim Laden des Templates: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
data := struct {
|
||||
Filename string
|
||||
}{
|
||||
Filename: filePath,
|
||||
}
|
||||
|
||||
err = tmpl.Execute(w, data)
|
||||
if err != nil {
|
||||
http.Error(w, "Fehler beim Rendern des Templates", http.StatusInternalServerError)
|
||||
log.Printf("Fehler beim Rendern des Templates: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
12
templates/viewImage.html
Normal file
12
templates/viewImage.html
Normal file
|
@ -0,0 +1,12 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Bild anzeigen</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Bildanzeige</h1>
|
||||
<!-- Verwenden des neuen Handlers für die Bild-URL -->
|
||||
<img src="/image/{{.Filename}}" alt="Hochgeladenes Bild">
|
||||
<p><a href="/">Zurück zum Upload</a></p>
|
||||
</body>
|
||||
</html>
|
Loading…
Reference in a new issue