-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
59 lines (49 loc) · 1.22 KB
/
server.go
File metadata and controls
59 lines (49 loc) · 1.22 KB
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
package main
import (
"io/ioutil"
"net/http"
)
const (
// StatusURLMissing error message for when URL is not specified
StatusURLMissing = "Parametar URL is missing in body request"
)
// Server is custom wrapper for listen and serve
type Server struct {
addr string
notify NotificationService
}
// NotificationService handles notification for server
type NotificationService interface {
OnRequest(string) error
}
// NewServer creates a new custom server
func NewServer(addr string, notifyService NotificationService) *Server {
if len(addr) == 0 {
addr = ":8080"
}
return &Server{addr: addr, notify: notifyService}
}
// ListenAndServe is a wrapper for http.ListenAndServe
func (s *Server) ListenAndServe() error {
return http.ListenAndServe(s.addr, s)
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusBadRequest)
return
}
buff, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusUnprocessableEntity)
w.Write([]byte(err.Error()))
return
}
if s.notify == nil {
return
}
err = s.notify.OnRequest(string(buff))
if err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte(err.Error()))
}
}