2019-10-15 21:17:07 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2019-10-18 12:46:20 +00:00
|
|
|
"flag"
|
2019-10-15 21:17:07 +00:00
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
2019-10-18 12:46:20 +00:00
|
|
|
"path"
|
2019-10-15 21:17:07 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/gorilla/mux"
|
|
|
|
"github.com/rs/zerolog"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
"github.com/stretchr/graceful"
|
|
|
|
)
|
|
|
|
|
2019-10-18 12:46:20 +00:00
|
|
|
var (
|
|
|
|
distPath = flag.String("dist", "frontend/dist", "path to dist files")
|
|
|
|
)
|
|
|
|
|
2019-10-15 21:17:07 +00:00
|
|
|
func main() {
|
2019-10-18 12:46:20 +00:00
|
|
|
flag.Parse()
|
2019-10-15 21:17:07 +00:00
|
|
|
log.Logger = log.Logger.Output(zerolog.ConsoleWriter{Out: os.Stderr})
|
|
|
|
zerolog.SetGlobalLevel(zerolog.DebugLevel)
|
|
|
|
s := server{"0.0.0.0:8080", "pub"}
|
|
|
|
s.serve()
|
|
|
|
}
|
|
|
|
|
|
|
|
func logger(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
log.Info().
|
|
|
|
Str("Path", r.URL.Path).
|
|
|
|
Str("Method", r.Method).
|
|
|
|
Msg("HTTP Request")
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
type server struct {
|
|
|
|
addr string
|
|
|
|
assetPath string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *server) handleMood(w http.ResponseWriter, r *http.Request) {
|
|
|
|
fmt.Fprintf(w, "hello")
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *server) indexHandler(entryPoint string) func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
fn := func(w http.ResponseWriter, r *http.Request) {
|
2019-10-18 12:46:20 +00:00
|
|
|
p := path.Join(*distPath, path.Clean(r.URL.Path))
|
|
|
|
f, err := os.Stat(p)
|
|
|
|
if !os.IsNotExist(err) && !f.IsDir() {
|
|
|
|
http.ServeFile(w, r, p)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
p = path.Join(p, "index.html")
|
|
|
|
if f, err := os.Stat(p); !os.IsNotExist(err) && !f.IsDir() {
|
|
|
|
http.ServeFile(w, r, p)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
http.ServeFile(w, r, path.Join(*distPath, entryPoint))
|
2019-10-15 21:17:07 +00:00
|
|
|
}
|
2019-10-18 12:46:20 +00:00
|
|
|
return fn
|
2019-10-15 21:17:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *server) routeSetup() *mux.Router {
|
|
|
|
r := mux.NewRouter()
|
|
|
|
api := r.PathPrefix("/v1/").Subrouter()
|
|
|
|
api.HandleFunc("/mood", s.handleMood).Methods("POST")
|
2019-10-18 12:46:20 +00:00
|
|
|
r.PathPrefix("/").HandlerFunc(s.indexHandler("/index.html"))
|
2019-10-15 21:17:07 +00:00
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *server) serve() {
|
|
|
|
middle := s.routeSetup()
|
|
|
|
log.Info().Str("addr", s.addr).Msg("serving HTTP")
|
|
|
|
graceful.Run(s.addr, 10*time.Second, middle)
|
|
|
|
}
|