57 lines
931 B
Go
57 lines
931 B
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"go-rest-api/handler"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gorilla/mux"
|
|
)
|
|
|
|
// Server struct
|
|
type Server struct {
|
|
port string
|
|
server http.Server
|
|
}
|
|
|
|
// NewServer func
|
|
func NewServer(port string) Server {
|
|
return Server{
|
|
port: port,
|
|
}
|
|
}
|
|
|
|
// Serve func
|
|
func (s *Server) Serve() {
|
|
r := mux.NewRouter()
|
|
|
|
handler.AttachArticleHandlersToRouter(r)
|
|
|
|
r.HandleFunc("/", s.handleDefault)
|
|
|
|
s.server = http.Server{
|
|
Addr: s.port,
|
|
Handler: r,
|
|
IdleTimeout: 120 * time.Second,
|
|
ReadTimeout: 1 * time.Second,
|
|
WriteTimeout: 1 * time.Second,
|
|
}
|
|
log.Print("Listening on", s.port)
|
|
|
|
err := s.server.ListenAndServe()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|
|
|
|
// Shutdown func
|
|
func (s *Server) Shutdown(tc context.Context) {
|
|
s.server.Shutdown(tc)
|
|
}
|
|
|
|
func (s *Server) handleDefault(w http.ResponseWriter, r *http.Request) {
|
|
w.Write([]byte(string("REST API. Get the fuck out!")))
|
|
}
|