Implement file removal in the backend.
[armadillo.git] / src / server.go
1 //
2 // Armadillo File Manager
3 // Copyright (c) 2010, Robert Sesek <http://www.bluestatic.org>
4 //
5 // This program is free software: you can redistribute it and/or modify it under
6 // the terms of the GNU General Public License as published by the Free Software
7 // Foundation, either version 3 of the License, or any later version.
8 //
9
10 package server
11
12 import (
13 "fmt"
14 "http"
15 "io"
16 "json"
17 "os"
18 "path"
19 "strings"
20 "./paths"
21 )
22
23 var dir, file = path.Split(path.Clean(os.Getenv("_")))
24 var kFrontEndFiles string = path.Join(dir, "fe")
25
26 func indexHandler(connection *http.Conn, request *http.Request) {
27 fd, err := os.Open(path.Join(kFrontEndFiles, "index.html"), os.O_RDONLY, 0)
28 if err != nil {
29 fmt.Print("Error opening file ", err.String(), "\n")
30 return
31 }
32 io.Copy(connection, fd)
33 }
34
35 func serviceHandler(connection *http.Conn, request *http.Request) {
36 if request.Method != "POST" {
37 io.WriteString(connection, "Error: Not a POST request")
38 return
39 }
40
41 switch request.FormValue("action") {
42 case "list":
43 files, err := paths.List(request.FormValue("path"))
44 if err != nil {
45 errorResponse(connection, err.String())
46 } else {
47 okResponse(connection, files)
48 }
49 case "remove":
50 err := paths.Remove(request.FormValue("path"))
51 if err != nil {
52 errorResponse(connection, err.String())
53 } else {
54 response := map[string] int {
55 "error" : 0,
56 }
57 okResponse(connection, response)
58 }
59 default:
60 errorResponse(connection, "Unhandled action")
61 }
62 }
63
64 func errorResponse(connection *http.Conn, message string) {
65 message = strings.Replace(message, paths.JailRoot, "/", -1)
66 response := map[string] string {
67 "error" : "-1",
68 "message" : message,
69 }
70 json_data, err := json.Marshal(response)
71
72 connection.SetHeader("Content-Type", "text/json")
73 if err != nil {
74 io.WriteString(connection, "{\"error\":\"-9\",\"message\":\"Internal encoding error\"}")
75 } else {
76 connection.Write(json_data)
77 }
78 }
79
80 func okResponse(connection *http.Conn, data interface{}) {
81 connection.SetHeader("Content-Type", "text/json")
82 json_data, err := json.Marshal(data)
83 if err != nil {
84 errorResponse(connection, "Internal encoding error")
85 } else {
86 connection.Write(json_data)
87 }
88 }
89
90 func RunFrontEnd(port int) {
91 mux := http.NewServeMux()
92 mux.HandleFunc("/", indexHandler)
93 mux.Handle("/fe/", http.FileServer(kFrontEndFiles, "/fe/"))
94 mux.HandleFunc("/service", serviceHandler)
95
96 error := http.ListenAndServe(fmt.Sprintf(":%d", port), mux)
97 fmt.Printf("error %v", error)
98 }