-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebserver-mux.go
60 lines (50 loc) · 1.48 KB
/
webserver-mux.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
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
//Article describes a article entity
type Article struct {
Name string `json:"name"`
Desc string `json:"desc"`
}
//Version defines the application current version
type Version struct {
Version int `json:"version"`
}
var articles = []Article{
Article{Name: "Sample", Desc: "Sample Description"},
Article{Name: "Sample2", Desc: "Sample Description 2"},
Article{Name: "Sample3", Desc: "Sample Description 3"},
Article{Name: "Sample4", Desc: "Sample Description 4"},
}
var articleMap map[string]Article = make(map[string]Article)
func getVersion(response http.ResponseWriter, request *http.Request) {
fmt.Fprintf(response, "%v\n", Version{Version: 1})
}
func getArticles(response http.ResponseWriter, request *http.Request) {
fmt.Fprintf(response, "%v\n", articles)
}
func init() {
insertArticlesIntoMap()
}
func insertArticlesIntoMap() {
for _, article := range articles {
articleMap[article.Name] = article
}
}
func getArticleByName(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
fmt.Fprintf(response, "%v\n", articleMap[vars["articleName"]])
}
func registerHandlerForApplication() {
myRouter := mux.NewRouter()
myRouter.HandleFunc("/version", getVersion).Methods("GET")
myRouter.HandleFunc("/articles", getArticles).Methods("GET")
myRouter.HandleFunc("/articles/{articleName}", getArticleByName)
http.ListenAndServe(":8080", myRouter)
}
func main() {
registerHandlerForApplication()
}