78 lines
1.7 KiB
Go
78 lines
1.7 KiB
Go
package main
|
|
|
|
import (
|
|
"flag"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
"time"
|
|
|
|
"github.com/gorilla/mux"
|
|
"github.com/rs/zerolog"
|
|
"github.com/rs/zerolog/log"
|
|
"github.com/stretchr/graceful"
|
|
)
|
|
|
|
var (
|
|
distPath = flag.String("dist", "frontend/dist", "path to dist files")
|
|
)
|
|
|
|
func main() {
|
|
flag.Parse()
|
|
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) {
|
|
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))
|
|
}
|
|
return fn
|
|
}
|
|
|
|
func (s *server) routeSetup() *mux.Router {
|
|
r := mux.NewRouter()
|
|
api := r.PathPrefix("/v1/").Subrouter()
|
|
api.HandleFunc("/mood", s.handleMood).Methods("POST")
|
|
r.PathPrefix("/").HandlerFunc(s.indexHandler("/index.html"))
|
|
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)
|
|
}
|