* Fix a bug in sendRequest_()
[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 "./paths"
20 )
21
22 var dir, file = path.Split(path.Clean(os.Getenv("_")))
23 var kFrontEndFiles string = path.Join(dir, "fe")
24
25 func indexHandler(connection *http.Conn, request *http.Request) {
26 fd, err := os.Open(path.Join(kFrontEndFiles, "index.html"), os.O_RDONLY, 0)
27 if err != nil {
28 fmt.Print("Error opening file ", err.String(), "\n")
29 return
30 }
31 io.Copy(connection, fd)
32 }
33
34 func serviceHandler(connection *http.Conn, request *http.Request) {
35 if request.Method != "POST" {
36 io.WriteString(connection, "Error: Not a POST request")
37 return
38 }
39
40 switch request.FormValue("action") {
41 case "list":
42 files, err := paths.List(request.FormValue("path"))
43 if err != nil {
44 errorResponse(connection, err.String())
45 } else {
46 okResponse(connection, files)
47 }
48 default:
49 errorResponse(connection, "Unhandled action")
50 }
51 }
52
53 func errorResponse(connection *http.Conn, message string) {
54 response := map[string] string {
55 "error": "-1",
56 "message": message,
57 }
58 json_data, err := json.Marshal(response)
59
60 connection.SetHeader("Content-Type", "text/json")
61 if err != nil {
62 io.WriteString(connection, "{\"error\":\"-9\",\"message\":\"Internal encoding error\"}")
63 } else {
64 connection.Write(json_data)
65 }
66 }
67
68 func okResponse(connection *http.Conn, data interface{}) {
69 connection.SetHeader("Content-Type", "text/json")
70 json_data, err := json.Marshal(data)
71 if err != nil {
72 errorResponse(connection, "Internal encoding error")
73 } else {
74 connection.Write(json_data)
75 }
76 }
77
78 func RunFrontEnd() {
79 mux := http.NewServeMux()
80 mux.HandleFunc("/", indexHandler)
81 mux.Handle("/fe/", http.FileServer(kFrontEndFiles, "/fe/"))
82 mux.HandleFunc("/service", serviceHandler)
83
84 error := http.ListenAndServe(":8084", mux)
85 fmt.Printf("error %v", error)
86 }