Add path listing service.
[armadillo.git] / src / server.go
1 package server
2
3 import (
4 "fmt"
5 "http"
6 "io"
7 "json"
8 "os"
9 "path"
10 "./paths"
11 )
12
13 const kFrontEndFiles = "/Users/rsesek/Projects/armadillo/out/fe/"
14
15 func indexHandler(connection *http.Conn, request *http.Request) {
16 fd, err := os.Open(path.Join(kFrontEndFiles, "index.html"), os.O_RDONLY, 0)
17 if err != nil {
18 fmt.Print("Error opening file ", err.String(), "\n")
19 return
20 }
21 io.Copy(connection, fd)
22 }
23
24 func serviceHandler(connection *http.Conn, request *http.Request) {
25 if request.Method != "POST" {
26 io.WriteString(connection, "Error: Not a POST request")
27 return
28 }
29
30 switch request.FormValue("action") {
31 case "list":
32 files, err := paths.List("./")
33 if err != nil {
34 errorResponse(connection, err.String())
35 } else {
36 okResponse(connection, files)
37 }
38 return
39 }
40
41 errorResponse(connection, "Unhandled action")
42 }
43
44 func errorResponse(connection *http.Conn, message string) {
45 response := map[string] string {
46 "error": "-1",
47 "message": message,
48 }
49 json_data, err := json.Marshal(response)
50
51 connection.SetHeader("Content-Type", "text/json")
52 if err != nil {
53 io.WriteString(connection, "{\"error\":\"-9\",\"message\":\"Internal encoding error\"}")
54 } else {
55 connection.Write(json_data)
56 }
57 }
58
59 func okResponse(connection *http.Conn, data interface{}) {
60 connection.SetHeader("Content-Type", "text/json")
61 json_data, err := json.Marshal(data)
62 if err != nil {
63 errorResponse(connection, "Internal encoding error")
64 } else {
65 connection.Write(json_data)
66 }
67 }
68
69 func RunFrontEnd() {
70 mux := http.NewServeMux()
71 mux.HandleFunc("/", indexHandler)
72 mux.Handle("/fe/", http.FileServer(kFrontEndFiles, "/fe/"))
73 mux.HandleFunc("/service", serviceHandler)
74
75 error := http.ListenAndServe(":8084", mux)
76 fmt.Printf("error %v", error)
77 }