-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
85 lines (71 loc) · 1.73 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"sync"
"github.com/colinfletch/goapiserver/platform/newsfeed"
"github.com/go-chi/chi"
)
const (
port = ":3000"
userAPIResp = `
Request received : %q endpoint
HTTP Method : %v
This is call %v to this API
`
countAPIResp = `
<p> Hello, World!
<p> Request received : %q endpoint
<p> HTTP Method : %v
<p> API Call Count: %v
`
)
var userCount int
type countHandler struct {
mu sync.Mutex //guards nil
n int
}
func userHandlerFunc(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World")
userCount++
out := fmt.Sprintf(userAPIResp, r.URL.Path, r.Method, userCount)
fmt.Fprintf(w, out)
}
func (h *countHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.mu.Lock()
defer h.mu.Unlock()
h.n++
out := fmt.Sprintf(countAPIResp, r.URL.Path, r.Method, h.n)
fmt.Fprintf(w, out)
fmt.Fprintf(w, "count is %d\n", h.n)
}
func main() {
http.HandleFunc("/users/", userHandlerFunc) //allows /users/deadpool etc
http.Handle("/count", new(countHandler)) // strict matching, only on exact endpoint
feed := newsfeed.New()
feed.Add(newsfeed.Item{
Title: "Something New!",
Post: "This is a new article post...",
})
r := chi.NewRouter()
//Get news
r.Get("/news", func(w http.ResponseWriter, r *http.Request) {
items := feed.GetAll()
json.NewEncoder(w).Encode(items)
})
//Post news
r.Post("/news", func(w http.ResponseWriter, r *http.Request) {
request := map[string]string{}
json.NewDecoder(r.Body).Decode(&request)
feed.Add(newsfeed.Item{
Title: request["title"],
Post: request["post"],
})
w.WriteHeader(201)
w.Write([]byte("Well Done!"))
})
fmt.Println("Serving on port ", port)
log.Fatal(http.ListenAndServe(port, r))
}