|
5 | 5 | package main |
6 | 6 |
|
7 | 7 | import ( |
| 8 | + "bytes" |
| 9 | + "encoding/json" |
8 | 10 | "fmt" |
| 11 | + "io" |
9 | 12 | "net/http" |
10 | 13 | "strings" |
11 | 14 | "time" |
@@ -47,7 +50,8 @@ func newServer(options ...func(s *server) error) (*server, error) { |
47 | 50 |
|
48 | 51 | func (s *server) init() { |
49 | 52 | s.mux.HandleFunc("/", s.handleEdit) |
50 | | - s.mux.HandleFunc("/fmt", handleFmt) |
| 53 | + s.mux.HandleFunc("/fmt", s.handleFmt) |
| 54 | + s.mux.HandleFunc("/version", s.handleVersion) |
51 | 55 | s.mux.HandleFunc("/vet", s.commandHandler("vet", vetCheck)) |
52 | 56 | s.mux.HandleFunc("/compile", s.commandHandler("prog", compileAndRun)) |
53 | 57 | s.mux.HandleFunc("/share", s.handleShare) |
@@ -90,3 +94,20 @@ func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
90 | 94 | } |
91 | 95 | s.mux.ServeHTTP(w, r) |
92 | 96 | } |
| 97 | + |
| 98 | +// writeJSONResponse JSON-encodes resp and writes to w with the given HTTP |
| 99 | +// status. |
| 100 | +func (s *server) writeJSONResponse(w http.ResponseWriter, resp interface{}, status int) { |
| 101 | + w.Header().Set("Content-Type", "application/json") |
| 102 | + var buf bytes.Buffer |
| 103 | + if err := json.NewEncoder(&buf).Encode(resp); err != nil { |
| 104 | + s.log.Errorf("error encoding response: %v", err) |
| 105 | + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) |
| 106 | + return |
| 107 | + } |
| 108 | + w.WriteHeader(status) |
| 109 | + if _, err := io.Copy(w, &buf); err != nil { |
| 110 | + s.log.Errorf("io.Copy(w, &buf): %v", err) |
| 111 | + return |
| 112 | + } |
| 113 | +} |
0 commit comments