60 lines
1.3 KiB
Go
60 lines
1.3 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"net/http"
|
||
|
"os"
|
||
|
"time"
|
||
|
|
||
|
"github.com/gorilla/mux"
|
||
|
"github.com/rs/zerolog"
|
||
|
"github.com/rs/zerolog/log"
|
||
|
"github.com/stretchr/graceful"
|
||
|
)
|
||
|
|
||
|
func main() {
|
||
|
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) {
|
||
|
http.ServeFile(w, r, entryPoint)
|
||
|
}
|
||
|
return http.HandlerFunc(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("dist/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)
|
||
|
}
|