2020-09-17 20:33:58 +02:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"go-rest-api/handler"
|
|
|
|
"net/http"
|
|
|
|
|
2020-09-26 22:38:38 +02:00
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
"github.com/labstack/echo/v4/middleware"
|
2020-09-17 20:33:58 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// Server struct
|
|
|
|
type Server struct {
|
|
|
|
port string
|
2020-09-26 22:38:38 +02:00
|
|
|
server *http.Server
|
2020-09-17 20:33:58 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewServer func
|
|
|
|
func NewServer(port string) Server {
|
|
|
|
return Server{
|
2020-09-26 22:38:38 +02:00
|
|
|
server: &http.Server{
|
|
|
|
Addr: port,
|
|
|
|
},
|
2020-09-17 20:33:58 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Serve func
|
|
|
|
func (s *Server) Serve() {
|
2020-09-26 22:38:38 +02:00
|
|
|
e := echo.New()
|
2020-09-17 20:33:58 +02:00
|
|
|
|
2020-09-26 22:38:38 +02:00
|
|
|
e.Use(middleware.Logger())
|
|
|
|
e.Use(middleware.Recover())
|
|
|
|
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
|
|
|
|
AllowOrigins: []string{"http://localhost:8000"},
|
|
|
|
AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
|
|
|
|
}))
|
2020-09-17 20:33:58 +02:00
|
|
|
|
2020-09-26 22:38:38 +02:00
|
|
|
handler.AttachArticleHandlersToRouter(e)
|
2020-09-17 20:33:58 +02:00
|
|
|
|
2020-09-26 22:38:38 +02:00
|
|
|
e.Static("/", "./public")
|
|
|
|
e.GET("/", s.defaultHandler)
|
2020-09-17 20:33:58 +02:00
|
|
|
|
2020-09-26 22:38:38 +02:00
|
|
|
e.Logger.Fatal(e.StartServer(s.server))
|
2020-09-17 20:33:58 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Shutdown func
|
|
|
|
func (s *Server) Shutdown(tc context.Context) {
|
|
|
|
s.server.Shutdown(tc)
|
|
|
|
}
|
|
|
|
|
2020-09-26 22:38:38 +02:00
|
|
|
func (s *Server) defaultHandler(c echo.Context) error {
|
|
|
|
return echo.NewHTTPError(http.StatusMethodNotAllowed, "Method not allowed.")
|
2020-09-17 20:33:58 +02:00
|
|
|
}
|