large refactor, fixes #2
This commit is contained in:
@ -1,102 +1,102 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/go-chi/chi/middleware"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/go-chi/chi/middleware"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type (
|
||||
Endpoint func(http.ResponseWriter, *http.Request) error
|
||||
Endpoint func(http.ResponseWriter, *http.Request) error
|
||||
|
||||
ErrResponse struct {
|
||||
Status int `json:"status,omitempty"`
|
||||
Err string `json:"error,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Details string `json:"details,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
RequestID string `json:"request,omitempty"`
|
||||
}
|
||||
ErrResponse struct {
|
||||
Status int `json:"status,omitempty"`
|
||||
Err string `json:"error,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Details string `json:"details,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
RequestID string `json:"request,omitempty"`
|
||||
}
|
||||
)
|
||||
|
||||
func Handle(handler Endpoint) http.HandlerFunc {
|
||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := handler(w, r); err != nil {
|
||||
WriteError(w, r, err)
|
||||
}
|
||||
}
|
||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := handler(w, r); err != nil {
|
||||
WriteError(w, r, err)
|
||||
}
|
||||
}
|
||||
|
||||
return http.HandlerFunc(fn)
|
||||
return http.HandlerFunc(fn)
|
||||
}
|
||||
|
||||
var nonErrorsCodes = map[int]bool{
|
||||
404: true,
|
||||
404: true,
|
||||
}
|
||||
|
||||
func errResponse(input interface{}) *ErrResponse {
|
||||
var res *ErrResponse
|
||||
var err interface{}
|
||||
var res *ErrResponse
|
||||
var err interface{}
|
||||
|
||||
switch input.(type) {
|
||||
case *HandlerError:
|
||||
e := input.(*HandlerError)
|
||||
res = &ErrResponse{
|
||||
Status: e.Status,
|
||||
Err: http.StatusText(e.Status),
|
||||
Message: e.Message,
|
||||
}
|
||||
err = e.Err
|
||||
default:
|
||||
res = &ErrResponse{
|
||||
Status: http.StatusInternalServerError,
|
||||
Err: http.StatusText(http.StatusInternalServerError),
|
||||
}
|
||||
err = input
|
||||
}
|
||||
switch input.(type) {
|
||||
case *HandlerError:
|
||||
e := input.(*HandlerError)
|
||||
res = &ErrResponse{
|
||||
Status: e.Status,
|
||||
Err: http.StatusText(e.Status),
|
||||
Message: e.Message,
|
||||
}
|
||||
err = e.Err
|
||||
default:
|
||||
res = &ErrResponse{
|
||||
Status: http.StatusInternalServerError,
|
||||
Err: http.StatusText(http.StatusInternalServerError),
|
||||
}
|
||||
err = input
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
switch err.(type) {
|
||||
case *error:
|
||||
e := err.(error)
|
||||
res.Details = e.Error()
|
||||
break
|
||||
default:
|
||||
res.Details = fmt.Sprintf("%+v", err)
|
||||
break
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
switch err.(type) {
|
||||
case *error:
|
||||
e := err.(error)
|
||||
res.Details = e.Error()
|
||||
break
|
||||
default:
|
||||
res.Details = fmt.Sprintf("%+v", err)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return res
|
||||
return res
|
||||
}
|
||||
|
||||
func WriteError(w http.ResponseWriter, r *http.Request, err interface{}) {
|
||||
hlog := log.With().
|
||||
Str("module", "http").
|
||||
Logger()
|
||||
hlog := log.With().
|
||||
Str("module", "http").
|
||||
Logger()
|
||||
|
||||
res := errResponse(err)
|
||||
res := errResponse(err)
|
||||
|
||||
if reqID := middleware.GetReqID(r.Context()); reqID != "" {
|
||||
res.RequestID = reqID
|
||||
}
|
||||
if reqID := middleware.GetReqID(r.Context()); reqID != "" {
|
||||
res.RequestID = reqID
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(res.Status)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(res.Status)
|
||||
|
||||
if err := json.NewEncoder(w).Encode(res); err != nil {
|
||||
hlog.Warn().Err(err).Msg("Failed writing json error response")
|
||||
}
|
||||
if err := json.NewEncoder(w).Encode(res); err != nil {
|
||||
hlog.Warn().Err(err).Msg("Failed writing json error response")
|
||||
}
|
||||
|
||||
if !nonErrorsCodes[res.Status] {
|
||||
logEntry := middleware.GetLogEntry(r)
|
||||
if logEntry != nil {
|
||||
logEntry.Panic(err, debug.Stack())
|
||||
} else {
|
||||
hlog.Error().Str("stack", string(debug.Stack())).Msgf("%+v", err)
|
||||
}
|
||||
}
|
||||
if !nonErrorsCodes[res.Status] {
|
||||
logEntry := middleware.GetLogEntry(r)
|
||||
if logEntry != nil {
|
||||
logEntry.Panic(err, debug.Stack())
|
||||
} else {
|
||||
hlog.Error().Str("stack", string(debug.Stack())).Msgf("%+v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -3,15 +3,15 @@ package endpoint
|
||||
import "fmt"
|
||||
|
||||
type HandlerError struct {
|
||||
Status int
|
||||
Message string
|
||||
Err error
|
||||
Status int
|
||||
Message string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *HandlerError) Error() string {
|
||||
if e.Err != nil {
|
||||
return fmt.Sprintf("%s: %s", e.Message, e.Err.Error())
|
||||
}
|
||||
if e.Err != nil {
|
||||
return fmt.Sprintf("%s: %s", e.Message, e.Err.Error())
|
||||
}
|
||||
|
||||
return e.Message
|
||||
return e.Message
|
||||
}
|
||||
|
87
server/internal/http/http.go
Normal file
87
server/internal/http/http.go
Normal file
@ -0,0 +1,87 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"n.eko.moe/neko/internal/config"
|
||||
"n.eko.moe/neko/internal/http/endpoint"
|
||||
"n.eko.moe/neko/internal/http/middleware"
|
||||
"n.eko.moe/neko/internal/websocket"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
logger zerolog.Logger
|
||||
router *chi.Mux
|
||||
http *http.Server
|
||||
conf *config.Server
|
||||
}
|
||||
|
||||
func New(conf *config.Server, webSocketHandler *websocket.WebSocketHandler) *Server {
|
||||
logger := log.With().Str("module", "webrtc").Logger()
|
||||
|
||||
router := chi.NewRouter()
|
||||
// router.Use(middleware.Recoverer) // Recover from panics without crashing server
|
||||
router.Use(middleware.RequestID) // Create a request ID for each request
|
||||
router.Use(middleware.Logger) // Log API request calls
|
||||
|
||||
router.Get("/ws", func(w http.ResponseWriter, r *http.Request) {
|
||||
webSocketHandler.Upgrade(w, r)
|
||||
})
|
||||
|
||||
fs := http.FileServer(http.Dir(conf.Static))
|
||||
router.Get("/*", func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := os.Stat(conf.Static + r.RequestURI); os.IsNotExist(err) {
|
||||
http.StripPrefix(r.RequestURI, fs).ServeHTTP(w, r)
|
||||
} else {
|
||||
fs.ServeHTTP(w, r)
|
||||
}
|
||||
})
|
||||
|
||||
router.NotFound(endpoint.Handle(func(w http.ResponseWriter, r *http.Request) error {
|
||||
return &endpoint.HandlerError{
|
||||
Status: http.StatusNotFound,
|
||||
Message: fmt.Sprintf("file '%s' is not found", r.RequestURI),
|
||||
}
|
||||
}))
|
||||
|
||||
server := &http.Server{
|
||||
Addr: conf.Bind,
|
||||
Handler: router,
|
||||
}
|
||||
|
||||
return &Server{
|
||||
logger: logger,
|
||||
router: router,
|
||||
http: server,
|
||||
conf: conf,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) Start() {
|
||||
if s.conf.Cert != "" && s.conf.Key != "" {
|
||||
go func() {
|
||||
if err := s.http.ListenAndServeTLS(s.conf.Cert, s.conf.Key); err != http.ErrServerClosed {
|
||||
s.logger.Panic().Err(err).Msg("unable to start https server")
|
||||
}
|
||||
}()
|
||||
s.logger.Info().Msgf("https listening on %s", s.http.Addr)
|
||||
} else {
|
||||
go func() {
|
||||
if err := s.http.ListenAndServe(); err != http.ErrServerClosed {
|
||||
s.logger.Panic().Err(err).Msg("unable to start http server")
|
||||
}
|
||||
}()
|
||||
s.logger.Warn().Msgf("http listening on %s", s.http.Addr)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) Shutdown() error {
|
||||
return s.http.Shutdown(context.Background())
|
||||
}
|
@ -61,13 +61,13 @@ func (e *entry) Write(status, bytes int, elapsed time.Duration) {
|
||||
res["elapsed"] = float64(elapsed.Nanoseconds()) / 1000000.0
|
||||
|
||||
e.fields["res"] = res
|
||||
e.fields["module"] = "api"
|
||||
e.fields["module"] = "http"
|
||||
|
||||
if len(e.errors) > 0 {
|
||||
e.fields["errors"] = e.errors
|
||||
log.Error().Fields(e.fields).Msgf("Request failed (%d)", status)
|
||||
log.Error().Fields(e.fields).Msgf("request failed (%d)", status)
|
||||
} else {
|
||||
log.Debug().Fields(e.fields).Msgf("Request complete (%d)", status)
|
||||
log.Debug().Fields(e.fields).Msgf("request complete (%d)", status)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -4,9 +4,9 @@ package middleware
|
||||
// a pointer so it fits in an interface{} without allocation. This technique
|
||||
// for defining context keys was copied from Go 1.7's new use of context in net/http.
|
||||
type ctxKey struct {
|
||||
name string
|
||||
name string
|
||||
}
|
||||
|
||||
func (k *ctxKey) String() string {
|
||||
return "neko/ctx/" + k.name
|
||||
return "neko/ctx/" + k.name
|
||||
}
|
||||
|
@ -4,21 +4,21 @@ package middleware
|
||||
// https://github.com/zenazn/goji/tree/master/web/middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http"
|
||||
|
||||
"n.eko.moe/neko/internal/http/endpoint"
|
||||
"n.eko.moe/neko/internal/http/endpoint"
|
||||
)
|
||||
|
||||
func Recoverer(next http.Handler) http.Handler {
|
||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if rvr := recover(); rvr != nil {
|
||||
endpoint.WriteError(w, r, rvr)
|
||||
}
|
||||
}()
|
||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if rvr := recover(); rvr != nil {
|
||||
endpoint.WriteError(w, r, rvr)
|
||||
}
|
||||
}()
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
return http.HandlerFunc(fn)
|
||||
return http.HandlerFunc(fn)
|
||||
}
|
||||
|
@ -1,14 +1,14 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
// Key to use when setting the request ID.
|
||||
@ -37,19 +37,19 @@ var reqid uint64
|
||||
// than a millionth of a percent chance of generating two colliding IDs.
|
||||
|
||||
func init() {
|
||||
hostname, err := os.Hostname()
|
||||
if hostname == "" || err != nil {
|
||||
hostname = "localhost"
|
||||
}
|
||||
var buf [12]byte
|
||||
var b64 string
|
||||
for len(b64) < 10 {
|
||||
rand.Read(buf[:])
|
||||
b64 = base64.StdEncoding.EncodeToString(buf[:])
|
||||
b64 = strings.NewReplacer("+", "", "/", "").Replace(b64)
|
||||
}
|
||||
hostname, err := os.Hostname()
|
||||
if hostname == "" || err != nil {
|
||||
hostname = "localhost"
|
||||
}
|
||||
var buf [12]byte
|
||||
var b64 string
|
||||
for len(b64) < 10 {
|
||||
rand.Read(buf[:])
|
||||
b64 = base64.StdEncoding.EncodeToString(buf[:])
|
||||
b64 = strings.NewReplacer("+", "", "/", "").Replace(b64)
|
||||
}
|
||||
|
||||
prefix = fmt.Sprintf("%s/%s", hostname, b64[0:10])
|
||||
prefix = fmt.Sprintf("%s/%s", hostname, b64[0:10])
|
||||
}
|
||||
|
||||
// RequestID is a middleware that injects a request ID into the context of each
|
||||
@ -58,32 +58,32 @@ func init() {
|
||||
// process, and where the last number is an atomically incremented request
|
||||
// counter.
|
||||
func RequestID(next http.Handler) http.Handler {
|
||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
requestID := r.Header.Get("X-Request-Id")
|
||||
if requestID == "" {
|
||||
myid := atomic.AddUint64(&reqid, 1)
|
||||
requestID = fmt.Sprintf("%s-%06d", prefix, myid)
|
||||
}
|
||||
ctx = context.WithValue(ctx, RequestIDKey, requestID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
}
|
||||
return http.HandlerFunc(fn)
|
||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
requestID := r.Header.Get("X-Request-Id")
|
||||
if requestID == "" {
|
||||
myid := atomic.AddUint64(&reqid, 1)
|
||||
requestID = fmt.Sprintf("%s-%06d", prefix, myid)
|
||||
}
|
||||
ctx = context.WithValue(ctx, RequestIDKey, requestID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
}
|
||||
return http.HandlerFunc(fn)
|
||||
}
|
||||
|
||||
// GetReqID returns a request ID from the given context if one is present.
|
||||
// Returns the empty string if a request ID cannot be found.
|
||||
func GetReqID(ctx context.Context) string {
|
||||
if ctx == nil {
|
||||
return ""
|
||||
}
|
||||
if reqID, ok := ctx.Value(RequestIDKey).(string); ok {
|
||||
return reqID
|
||||
}
|
||||
return ""
|
||||
if ctx == nil {
|
||||
return ""
|
||||
}
|
||||
if reqID, ok := ctx.Value(RequestIDKey).(string); ok {
|
||||
return reqID
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// NextRequestID generates the next request ID in the sequence.
|
||||
func NextRequestID() uint64 {
|
||||
return atomic.AddUint64(&reqid, 1)
|
||||
return atomic.AddUint64(&reqid, 1)
|
||||
}
|
||||
|
@ -17,7 +17,7 @@ func JSON(w http.ResponseWriter, data interface{}, status int) error {
|
||||
if err != nil {
|
||||
return &endpoint.HandlerError{
|
||||
Status: http.StatusInternalServerError,
|
||||
Message: "Unable to write JSON response",
|
||||
Message: "unable to write JSON response",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user