-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathserver.go
More file actions
67 lines (56 loc) · 1.47 KB
/
server.go
File metadata and controls
67 lines (56 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"os"
"boot.dev/linko/internal/store"
)
type server struct {
httpServer *http.Server
store store.Store
cancel context.CancelFunc
}
func newServer(store store.Store, port int, cancel context.CancelFunc) *server {
mux := http.NewServeMux()
srv := &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: mux,
}
s := &server{
httpServer: srv,
store: store,
cancel: cancel,
}
mux.HandleFunc("GET /", s.handlerIndex)
mux.Handle("POST /api/login", s.authMiddleware(http.HandlerFunc(s.handlerLogin)))
mux.Handle("POST /api/shorten", s.authMiddleware(http.HandlerFunc(s.handlerShortenLink)))
mux.Handle("GET /api/stats", s.authMiddleware(http.HandlerFunc(s.handlerStats)))
mux.Handle("GET /api/urls", s.authMiddleware(http.HandlerFunc(s.handlerListURLs)))
mux.HandleFunc("GET /{shortCode}", s.handlerRedirect)
mux.HandleFunc("POST /admin/shutdown", s.handlerShutdown)
return s
}
func (s *server) start() error {
ln, err := net.Listen("tcp", s.httpServer.Addr)
if err != nil {
return err
}
if err := s.httpServer.Serve(ln); !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
}
func (s *server) shutdown(ctx context.Context) error {
return s.httpServer.Shutdown(ctx)
}
func (s *server) handlerShutdown(w http.ResponseWriter, r *http.Request) {
if os.Getenv("ENV") == "production" {
http.NotFound(w, r)
return
}
w.WriteHeader(http.StatusOK)
go s.cancel()
}