rest-api/server.go

50 lines
833 B
Go
Raw Normal View History

2020-09-15 23:09:07 +02:00
package main
import (
2020-09-17 18:01:18 +02:00
"context"
2020-09-15 23:09:07 +02:00
"log"
"net/http"
2020-09-17 18:01:18 +02:00
"time"
"github.com/gorilla/mux"
2020-09-15 23:09:07 +02:00
)
// Server base struct
type Server struct {
2020-09-17 18:01:18 +02:00
port string
server http.Server
2020-09-15 23:09:07 +02:00
}
func (s *Server) serve() {
2020-09-17 18:01:18 +02:00
sm := mux.NewRouter()
sm.Handle("/", s.handle())
sm.Handle("/articles", getAllArticles())
2020-09-15 23:09:07 +02:00
2020-09-17 18:01:18 +02:00
serv := &http.Server{
Addr: s.port,
Handler: sm,
IdleTimeout: 120 * time.Second,
ReadTimeout: 1 * time.Second,
WriteTimeout: 1 * time.Second,
}
s.server = *serv
2020-09-15 23:09:07 +02:00
log.Print("Listening on", s.port)
2020-09-17 18:01:18 +02:00
err := serv.ListenAndServe()
if err != nil {
log.Fatal(err)
}
2020-09-15 23:09:07 +02:00
}
func (s *Server) handle() http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(string("Hello World")))
}
return http.HandlerFunc(fn)
}
2020-09-17 18:01:18 +02:00
func (s *Server) shutdown(tc context.Context) {
s.server.Shutdown(tc)
}