-
Notifications
You must be signed in to change notification settings - Fork 4
/
http.go
102 lines (87 loc) · 2.23 KB
/
http.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
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
// Copyright 2014 go-beacon authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/fiorix/go-web/httpxtra"
"github.com/gorilla/context"
"github.com/fiorix/go-redis/redis"
)
type httpServer struct {
config *configFile
redis *redis.Client
}
func (s *httpServer) init(cf *configFile, rc *redis.Client) {
s.config = cf
s.redis = rc
// Initialize http handlers.
s.route()
}
func (s *httpServer) ListenAndServe() {
if s.config.HTTP.Addr == "" {
return
}
srv := http.Server{
Addr: s.config.HTTP.Addr,
Handler: httpxtra.Handler{Logger: httpLogger},
}
log.Println("Starting HTTP server on", s.config.HTTP.Addr)
log.Fatal(srv.ListenAndServe())
}
func (s *httpServer) ListenAndServeTLS() {
if s.config.HTTPS.Addr == "" {
return
}
srv := http.Server{
Addr: s.config.HTTPS.Addr,
Handler: httpxtra.Handler{Logger: httpLogger},
}
log.Println("Starting HTTPS server on", s.config.HTTPS.Addr)
log.Fatal(srv.ListenAndServeTLS(
s.config.HTTPS.CertFile,
s.config.HTTPS.KeyFile,
))
}
// httpError renders the default error message based on
// the status code, and sets the "log" context variable with the error.
func httpError(w http.ResponseWriter, r *http.Request, code int, msg interface{}) {
http.Error(w, http.StatusText(code), code)
if msg != nil {
context.Set(r, "log", msg)
}
}
// httpLogger is called at the end of every HTTP request. It dumps one
// log line per request.
//
// The "log" context variable can be set by handlers to add extra
// information to the log message, such as database or template errors.
func httpLogger(r *http.Request, created time.Time, status, bytes int) {
//fmt.Println(httpxtra.ApacheCommonLog(r, created, status, bytes))
log.Printf("%s %d %s %q (%s) :: %d bytes in %s%s",
logProto(r),
status,
r.Method,
r.URL.Path,
remoteIP(r),
bytes,
time.Since(created),
logMsg(r),
)
}
func logProto(r *http.Request) string {
if r.TLS == nil {
return "HTTP"
}
return "HTTPS"
}
func logMsg(r *http.Request) string {
if msg := context.Get(r, "log"); msg != nil {
defer context.Clear(r)
return fmt.Sprintf(" (%s)", msg)
}
return ""
}