Skip to content

Commit a9a61fa

Browse files
committed
Added ability to serve index.html along with static content (until html plugin will provide more flexibility)
1 parent f505f9b commit a9a61fa

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

example/index.html

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<html>
2+
<head>
3+
<title></title>
4+
</head>
5+
<body>
6+
<h1></h1>
7+
Hello world
8+
<img src="/static/material.jpg" />
9+
</body>
10+
</html>

main.go

+21
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"regexp"
1414
"strconv"
1515
"time"
16+
"io/ioutil"
1617
)
1718

1819
func getRequestParams(r *http.Request, urlParams map[string]interface{}) (map[string]interface{}, error) {
@@ -130,6 +131,20 @@ func handler(api *Api, route *Route, version int) func(http.ResponseWriter, *htt
130131
}
131132
}
132133

134+
var indexHtml []byte
135+
136+
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
137+
if len(indexHtml) == 0 {
138+
content, err := ioutil.ReadFile("index.html")
139+
if err != nil {
140+
indexHtml = []byte(err.Error())
141+
} else {
142+
indexHtml = content
143+
}
144+
}
145+
w.Write(indexHtml)
146+
}
147+
133148
var db *sql.DB
134149

135150
func main() {
@@ -146,6 +161,9 @@ func main() {
146161
}
147162
defer db.Close()
148163
router := httprouter.New()
164+
if _, err := os.Stat("./index.html"); err == nil {
165+
router.GET("/", Index)
166+
}
149167
for _, route := range api.Routes {
150168
if route.Method == "GET" {
151169
router.GET(route.Path, handler(api, route, 0))
@@ -184,6 +202,9 @@ func main() {
184202
if len(os.Args) > 1 {
185203
port = os.Args[1]
186204
}
205+
if _, err := os.Stat("./static"); err == nil {
206+
router.ServeFiles("/static/*filepath", http.Dir("static"))
207+
}
187208
log.Fatal(http.ListenAndServe(":"+port, router))
188209
}
189210

0 commit comments

Comments
 (0)