This repository has been archived by the owner on Jan 18, 2024. It is now read-only.
/
backend.go
71 lines (56 loc) · 1.58 KB
/
backend.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package server
import (
"fmt"
"net/http"
"github.com/nu7hatch/gouuid"
"github.com/gen2brain/acra-go/acra"
"github.com/gen2brain/acra-go/database"
)
// Backend struct
type Backend struct {
DB database.DB
}
// NewBackend returns new Backend
func NewBackend(db database.DB) *Backend {
return &Backend{db}
}
// ServeHTTP handles requests on incoming connections
func (b *Backend) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var err error
if r.Method != "POST" && r.Method != "PUT" {
msg := fmt.Sprintf("405 Method Not Allowed (%s)", r.Method)
http.Error(w, msg, http.StatusMethodNotAllowed)
return
}
contentType := r.Header.Get("Content-type")
if contentType != "application/json" && contentType != "application/x-www-form-urlencoded" {
msg := fmt.Sprintf("415 Unsupported Media Type (%s)", contentType)
http.Error(w, msg, http.StatusUnsupportedMediaType)
return
}
report := acra.Report{}
decoder := acra.NewDecoder(r.Body)
err = decoder.Decode(&report)
if err != nil {
msg := fmt.Sprintf("400 Bad Request (%s)", err.Error())
http.Error(w, msg, http.StatusBadRequest)
return
}
defer r.Body.Close()
if report.ReportID == "" {
id, err := uuid.NewV4()
if err != nil {
msg := fmt.Sprintf("500 Internal Server Error (%s)", err.Error())
http.Error(w, msg, http.StatusInternalServerError)
return
}
report.ReportID = id.String()
}
err = b.DB.Put(report.ReportID, report)
if err != nil {
msg := fmt.Sprintf("500 Internal Server Error (%s)", err.Error())
http.Error(w, msg, http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}