Last active
August 29, 2015 14:11
-
-
Save PhilmacFLy/561d6090f8dc2c4f2fa7 to your computer and use it in GitHub Desktop.
This file contains 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" | |
"html/template" | |
"io" | |
"net/http" | |
"os" | |
"path/filepath" | |
) | |
var uploadalert string | |
var filetowrite string | |
func handler(w http.ResponseWriter, r *http.Request) { | |
//title := "moodlights" | |
t, _ := template.ParseFiles("templates/template.html") | |
t.Execute(w, nil) | |
} | |
func statichandler(w http.ResponseWriter, r *http.Request) { | |
http.ServeFile(w, r, r.URL.Path[1:]) | |
} | |
func recieveHandler(w http.ResponseWriter, r *http.Request) { | |
file, header, err := r.FormFile("file") // the FormFile function takes in the POST input id file | |
defer file.Close() | |
if err != nil { | |
fmt.Fprintln(w, err) | |
return | |
} | |
fmt.Println(filepath.Ext(header.Filename)) | |
if filepath.Ext(header.Filename) != ".lua" { | |
uploadalert = "<div class=\"alert alert-danger\" role=\"alert\"><b>Oh snap!</b> File doesn't have .lua extension</div>" | |
http.Redirect(w, r, "/upload", http.StatusFound) | |
return | |
} | |
out, err := os.Create("uploaded/" + header.Filename) | |
if err != nil { | |
//fmt.Fprintf(w, "Unable to create file: %s", err.Error()) | |
errstring := err.Error() | |
uploadalert = "<div class=\"alert alert-danger\" role=\"alert\"><b>Oh snap!</b> Unable to create file: " + errstring + "</div>" | |
http.Redirect(w, r, "/upload", http.StatusFound) | |
return | |
} | |
defer out.Close() | |
// write the content from POST to the file | |
_, err = io.Copy(out, file) | |
if err != nil { | |
//fmt.Fprintln(w, err) | |
errstring := err.Error() | |
uploadalert = "<div class=\"alert alert-danger\" role=\"alert\"><b>Oh snap!</b> " + errstring + "</div>" | |
http.Redirect(w, r, "/upload", http.StatusFound) | |
return | |
} | |
uploadalert = "<div class=\"alert alert-success\" role=\"alert\"><b>Well done!</b> File uploaded</div>" | |
http.Redirect(w, r, "/upload", http.StatusFound) | |
fmt.Println("Info:", "File uploaded successfully:", header.Filename) | |
//fmt.Fprintf(w, "File uploaded successfully : ") | |
//fmt.Fprintf(w, header.Filename) | |
} | |
func main() { | |
http.HandleFunc("/", handler) | |
http.HandleFunc("/static/", statichandler) | |
http.HandleFunc("/templates", statichandler) | |
httpListenAndServe(":8080", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment