Skip to content

Commit f75042d

Browse files
committed
Add logger
1 parent bb4f4cb commit f75042d

File tree

7 files changed

+187
-14
lines changed

7 files changed

+187
-14
lines changed

example/health-check.json

Whitespace-only changes.

go-json-server.go

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@ package main
22

33
import (
44
"bytes"
5-
"encoding/csv"
65
"encoding/json"
76
"fmt"
87
"io/ioutil"
98
"log"
109
"net/http"
1110
"os"
1211
"strconv"
12+
13+
"github.com/tkc/go-json-server/src/logger"
1314
)
1415

1516
const (
@@ -127,7 +128,7 @@ func main() {
127128
func response(w http.ResponseWriter, r *http.Request) {
128129

129130
r.ParseForm()
130-
accessLog(r)
131+
logger.AccessLog(r)
131132

132133
w.Header().Set("Access-Control-Allow-Origin", "*")
133134
w.Header().Set("Access-Control-Allow-Credentials", "true")
@@ -159,15 +160,3 @@ func path2Response(path string) string {
159160
buf.ReadFrom(file)
160161
return buf.String()
161162
}
162-
163-
func accessLog(r *http.Request) {
164-
file, err := os.OpenFile("log.csv", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
165-
if err != nil {
166-
log.Fatal(err)
167-
}
168-
defer file.Close()
169-
s := []string{r.Method, r.Host, r.Proto, r.RequestURI, r.RemoteAddr}
170-
writer := csv.NewWriter(file)
171-
writer.Write(s)
172-
writer.Flush()
173-
}

go.mod

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
module github.com/tkc/go-json-server
2+
3+
go 1.13
4+
5+
require (
6+
github.com/spf13/cast v1.3.1
7+
github.com/stretchr/testify v1.5.1
8+
)

go.sum

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
2+
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
3+
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
4+
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
5+
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
6+
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
7+
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
8+
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
9+
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
10+
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
11+
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
12+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
13+
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
14+
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

src/logger/logger.go

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package logger
2+
3+
import (
4+
"encoding/csv"
5+
"encoding/json"
6+
"fmt"
7+
"io"
8+
"log"
9+
stdlog "log"
10+
"net/http"
11+
"os"
12+
"strconv"
13+
)
14+
15+
type stdLogger struct {
16+
stderr *stdlog.Logger
17+
stdout *stdlog.Logger
18+
}
19+
20+
func CreateLogger() *stdLogger {
21+
return &stdLogger{
22+
stdout: stdlog.New(os.Stdout, "", 0),
23+
stderr: stdlog.New(os.Stderr, "", 0),
24+
}
25+
}
26+
27+
func (l *stdLogger) AccessLog(r *http.Request) {
28+
file, err := os.OpenFile("log.csv", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
29+
if err != nil {
30+
log.Fatal(err)
31+
}
32+
33+
defer file.Close()
34+
35+
jsonBody := dumpJsonBoddy(r)
36+
37+
s := []string{r.Method, r.Host, r.Proto, r.RequestURI, r.RemoteAddr, jsonBody}
38+
writer := csv.NewWriter(file)
39+
writer.Write(s)
40+
writer.Flush()
41+
}
42+
43+
func dumpJsonBoddy(req *http.Request) string {
44+
45+
if req.Method == "GET" {
46+
return ""
47+
}
48+
49+
if req.Header.Get("Content-Type") != "application/json" {
50+
return ""
51+
}
52+
53+
length, err := strconv.Atoi(req.Header.Get("Content-Length"))
54+
55+
if err != nil {
56+
return ""
57+
}
58+
59+
body := make([]byte, length)
60+
length, err = req.Body.Read(body)
61+
62+
if err != nil && err != io.EOF {
63+
return ""
64+
}
65+
66+
var jsonBody map[string]interface{}
67+
err = json.Unmarshal(body[:length], &jsonBody)
68+
69+
if err != nil {
70+
return ""
71+
}
72+
73+
s := fmt.Sprintf("%v", jsonBody)
74+
return s
75+
}
76+
77+
func (l *stdLogger) Printf(format string, args ...interface{}) {
78+
l.stdout.Printf(format, args...)
79+
}
80+
81+
func (l *stdLogger) Errorf(format string, args ...interface{}) {
82+
l.stderr.Printf(format, args...)
83+
}
84+
85+
func (l *stdLogger) Fatalf(format string, args ...interface{}) {
86+
l.stderr.Fatalf(format, args...)
87+
}

src/logger/logger_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package logger
2+
3+
import (
4+
"bytes"
5+
"net/http"
6+
"testing"
7+
8+
"github.com/spf13/cast"
9+
"github.com/stretchr/testify/assert"
10+
)
11+
12+
func TestGetNonReadRecord(t *testing.T) {
13+
14+
url := "example.com"
15+
content := `{"integer":1,"string":"xyz", "object": { "element": 1 } , "array": [1, 2, 3]}`
16+
byte := []byte(content)
17+
18+
body := bytes.NewReader(byte)
19+
req, _ := http.NewRequest("POST", url, body)
20+
21+
req.Header.Set("Content-Type", "application/json")
22+
req.Header.Set("Content-Length", cast.ToString(len(content)))
23+
24+
result := dumpJsonBoddy(req)
25+
assert.Equal(t, result, "map[array:[1 2 3] integer:1 object:map[element:1] string:xyz]")
26+
}

test/main.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"io"
7+
"log"
8+
"net/http"
9+
"strconv"
10+
)
11+
12+
func dumpJsonRequestHandlerFunc(w http.ResponseWriter, req *http.Request) {
13+
14+
if req.Header.Get("Content-Type") != "application/json" {
15+
w.WriteHeader(http.StatusBadRequest)
16+
return
17+
}
18+
19+
length, err := strconv.Atoi(req.Header.Get("Content-Length"))
20+
if err != nil {
21+
w.WriteHeader(http.StatusInternalServerError)
22+
return
23+
}
24+
25+
log.Print(length)
26+
27+
body := make([]byte, length)
28+
length, err = req.Body.Read(body)
29+
30+
if err != nil && err != io.EOF {
31+
w.WriteHeader(http.StatusInternalServerError)
32+
return
33+
}
34+
35+
var jsonBody map[string]interface{}
36+
err = json.Unmarshal(body[:length], &jsonBody)
37+
if err != nil {
38+
w.WriteHeader(http.StatusInternalServerError)
39+
return
40+
}
41+
42+
fmt.Printf("%v\n", jsonBody)
43+
// w.WriteHeader(http.StatusOK)
44+
}
45+
46+
func main() {
47+
http.HandleFunc("/json", dumpJsonRequestHandlerFunc)
48+
http.ListenAndServe(":8080", nil)
49+
}

0 commit comments

Comments
 (0)