Add GPL file headers
[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 return
49 }
50
51 errorResponse(connection, "Unhandled action")
52 }
53
54 func errorResponse(connection *http.Conn, message string) {
55 response := map[string] string {
56 "error": "-1",
57 "message": message,
58 }
59 json_data, err := json.Marshal(response)
60
61 connection.SetHeader("Content-Type", "text/json")
62 if err != nil {
63 io.WriteString(connection, "{\"error\":\"-9\",\"message\":\"Internal encoding error\"}")
64 } else {
65 connection.Write(json_data)
66 }
67 }
68
69 func okResponse(connection *http.Conn, data interface{}) {
70 connection.SetHeader("Content-Type", "text/json")
71 json_data, err := json.Marshal(data)
72 if err != nil {
73 errorResponse(connection, "Internal encoding error")
74 } else {
75 connection.Write(json_data)
76 }
77 }
78
79 func RunFrontEnd() {
80 mux := http.NewServeMux()
81 mux.HandleFunc("/", indexHandler)
82 mux.Handle("/fe/", http.FileServer(kFrontEndFiles, "/fe/"))
83 mux.HandleFunc("/service", serviceHandler)
84
85 error := http.ListenAndServe(":8084", mux)
86 fmt.Printf("error %v", error)
87 }