-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.go
More file actions
177 lines (149 loc) · 4.11 KB
/
server.go
File metadata and controls
177 lines (149 loc) · 4.11 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package main
import (
"context"
"flag"
"fmt"
"io"
"net/http"
"os"
"os/signal"
"time"
"github.com/artemzi/olx-parser/OlxClient"
"github.com/artemzi/olx-parser/version"
"github.com/bitly/go-simplejson"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
"github.com/artemzi/olx-parser/entities"
"gopkg.in/mgo.v2"
"encoding/json"
)
const DEFAULTPORT = "8080"
func healthz(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
io.WriteString(w, `Ok`)
}
func info(w http.ResponseWriter, r *http.Request) {
info := simplejson.New()
info.Set("version", version.RELEASE)
info.Set("commit", version.COMMIT)
info.Set("repo", version.REPO)
payload, err := info.MarshalJSON()
if err != nil {
log.Error(err)
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
w.Write(payload)
}
func root(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
io.WriteString(w, fmt.Sprintf("PARSER v%s\n", version.RELEASE))
}
// loggingMiddleware used for routes logging
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Info(fmt.Sprintf("%s: %s", r.Method, r.RequestURI))
next.ServeHTTP(w, r)
})
}
// logging is wrapper for NotFoundHandler
func logging(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Warn(fmt.Sprintf("Not Found (%s) %s", r.Method, r.RequestURI))
f(w, r)
}
}
func init() {
switch version.STAGE {
case "dev":
log.SetLevel(log.DebugLevel)
case "prod":
f, err := os.OpenFile(fmt.Sprintf("./storage/logs/%s.log",
time.Now().Local().Format("2006-01-02")),
os.O_APPEND|os.O_WRONLY|os.O_CREATE,
0755)
if err != nil {
log.Error(err)
}
log.SetFormatter(&log.JSONFormatter{})
log.SetOutput(f)
log.SetLevel(log.InfoLevel)
}
}
func main() {
var wait time.Duration
flag.DurationVar(&wait, "graceful-timeout",
time.Second*15,
"the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m")
flag.Parse()
port := os.Getenv("SERVICE_PORT")
if len(port) == 0 {
port = DEFAULTPORT
}
r := mux.NewRouter()
r.HandleFunc("/", root).Methods("GET")
r.HandleFunc("/info", info).Methods("GET")
r.HandleFunc("/healthz", healthz).Methods("GET")
r.HandleFunc("/adverts", func(w http.ResponseWriter, r *http.Request) { // TODO
err := olxclient.Run()
if err != nil {
log.Fatal(err)
}
session, err := mgo.Dial("0.0.0.0")
if err != nil {
log.Fatal(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("olxparser").C("adverts")
var adverts []*entities.Adverts
err = c.Find(nil).Limit(10).All(&adverts)
if err != nil {
panic(err)
}
out, err := json.Marshal(&entities.AdvertsResponse{
Size: len(adverts),
Adverts: adverts,
})
if err != nil {
log.Fatal(err)
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
w.Write(out)
}).Methods("POST")
r.Use(loggingMiddleware)
r.NotFoundHandler = http.HandlerFunc(logging(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
io.WriteString(w, `Not Found`)
}))
srv := &http.Server{
Addr: fmt.Sprintf("0.0.0.0:%s", port),
// Good practice to set timeouts to avoid Slowloris attacks.
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: r,
}
go func() {
log.Debug(fmt.Sprintf("Server started on: http://0.0.0.0:%s", port))
if err := srv.ListenAndServe(); err != nil {
log.Error(err)
}
}()
// ====== Graceful shutdown
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
// Doesn't block if no connections, but will otherwise wait
// until the timeout deadline.
srv.Shutdown(ctx)
// Optionally, you could run srv.Shutdown in a goroutine and block on
// <-ctx.Done() if your application should wait for other services
// to finalize based on context cancellation.
log.Info("shutting down")
os.Exit(0)
// ==========
}