-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
66 lines (56 loc) · 1.42 KB
/
server.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
package main
import (
"encoding/json"
"log"
"net/http"
"time"
"github.com/barnybug/gogsmmodem"
"github.com/google/uuid"
"github.com/jinzhu/gorm"
)
func createIncomingMessageHandler(db *gorm.DB, modem *gogsmmodem.Modem) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
// read struct
decoder := json.NewDecoder(r.Body)
var m Message
err := decoder.Decode(&m)
defer r.Body.Close()
if err != nil {
http.Error(w, "400 Bad request.", http.StatusBadRequest)
return
}
// save to db
m.Incoming = false
m.ID = uuid.New().String()
m.Time = time.Now().UTC()
db.Create(&m)
// send
log.Printf("Sending message %v: %v\n", m.Number, m.Body)
err = modem.SendMessage(m.Number, m.Body)
if err != nil {
http.Error(w, "500 Failed to send.", http.StatusInternalServerError)
return
}
// mark handled and update in db
m.Handled = true
db.Save(&m)
// respond to http request
w.WriteHeader(http.StatusOK)
str, _ := json.Marshal(m)
w.Write([]byte(str))
default:
http.Error(w, "404 not found.", http.StatusNotFound)
return
}
}
}
func listenOnHTTP(db *gorm.DB, modem *gogsmmodem.Modem, port string) chan error {
errorChannel := make(chan error, 1)
http.HandleFunc("/api/messages", createIncomingMessageHandler(db, modem))
for {
err := http.ListenAndServe(":"+port, nil)
errorChannel <- err
}
}