-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
88 lines (79 loc) · 2.07 KB
/
Copy pathmain.go
File metadata and controls
88 lines (79 loc) · 2.07 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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/afshin/sleuth-example/types"
"github.com/gorilla/mux"
)
const commentsURL = "http://localhost:9871/comments/%s"
var (
client = new(http.Client)
data = make(map[string]*types.Article) // Key is article GUID.
)
func init() {
var err error
var raw []byte
if raw, err = ioutil.ReadFile("data.json"); err != nil {
panic("Could not read data file: " + err.Error())
}
var all []*types.Article
if err = json.Unmarshal(raw, &all); err != nil {
panic("Could not parse: " + err.Error())
}
for _, article := range all {
data[article.GUID] = article
}
}
func getData(guid string, includeComments bool) (article *types.Article) {
datum, ok := data[guid]
if !ok {
return
}
// Data source is immutable, so copy the data.
article = &types.Article{
GUID: datum.GUID,
Byline: datum.Byline,
Headline: datum.Headline,
URL: datum.URL,
Timestamp: datum.Timestamp}
if !includeComments {
return
}
url := fmt.Sprintf(commentsURL, guid)
req, _ := http.NewRequest("GET", url, nil)
if res, err := client.Do(req); err == nil {
response := new(types.CommentResponse)
if err := json.NewDecoder(res.Body).Decode(response); err == nil {
article.Comments = response.Data
}
}
return
}
func handler(res http.ResponseWriter, req *http.Request) {
log.Println("GET " + req.URL.String())
response := new(types.ArticleResponse)
guid := mux.Vars(req)["guid"]
include := strings.ToLower(req.URL.Query().Get("includecomments"))
if article := getData(guid, include == "true"); article != nil {
response.Data = article
response.Success = true
res.WriteHeader(http.StatusOK)
} else {
response.Success = false
response.Message = guid + " not found"
res.WriteHeader(http.StatusNotFound)
}
output, _ := json.Marshal(response)
res.Header().Set("Content-Type", "application/json")
res.Write(output)
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/articles/{guid}", handler).Methods("GET")
fmt.Println("ready...")
http.ListenAndServe(":9872", router)
}