-
Notifications
You must be signed in to change notification settings - Fork 6
/
http.go
81 lines (71 loc) · 2.19 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
package api
import (
"encoding/json"
"errors"
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/cors"
)
// NewHandler initializes a new feed router
func NewHandler(s service) *chi.Mux {
r := chi.NewRouter()
cors := cors.New(cors.Options{
// AllowedOrigins: []string{"https://foo.com"}, // Use this to allow specific origin hosts
AllowedOrigins: []string{"*"},
// AllowOriginFunc: func(r *http.Request, origin string) bool { return true },
AllowedMethods: []string{"GET", "POST", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300, // Maximum value not ignored by any of major browsers
})
r.Use(cors.Handler)
// Public routes
r.Group(func(r chi.Router) {
r.Get("/list", getPluginListHandler(s))
r.Get("/{plugin}/{format}", getFeedHandler(s))
})
return r
}
// getFeedHandler returns a feed in a specified format
func getFeedHandler(s service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
plugin := chi.URLParam(r, "plugin")
if plugin == "" {
http.Error(w, errors.New("plugin not allowed to be empty").Error(), http.StatusInternalServerError)
return
}
format := chi.URLParam(r, "format")
if format == "" {
format = "rss"
}
s, err := s.ServeFeed(format, plugin)
if err != nil {
http.Error(w, errors.New("there was an error serving the feed").Error(), http.StatusInternalServerError)
return
}
switch format {
case "atom":
w.Header().Set("Content-Type", "application/atom+xml")
case "json":
w.Header().Set("Content-Type", "application/json")
default:
w.Header().Set("Content-Type", "application/rss+xml")
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(s))
}
}
// getPluginListHandler returns a list of all available plugins
func getPluginListHandler(s service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
plugins := s.ListFeeds()
b, err := json.Marshal(plugins)
if err != nil {
http.Error(w, errors.New("there was an error listing the plugins").Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(b)
}
}