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