-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
73 lines (62 loc) · 1.38 KB
/
server.go
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
68
69
70
71
72
73
package api
import (
"errors"
"net/http"
"github.com/fabiante/persurl/api/res"
"github.com/fabiante/persurl/app"
"github.com/gin-gonic/gin"
)
type Server struct {
service *app.Service
}
func NewServer(service *app.Service) *Server {
return &Server{service: service}
}
func (s *Server) Resolve(ctx *gin.Context) {
domain := ctx.Param("domain")
name := ctx.Param("name")
target, err := s.service.Resolve(domain, name)
switch true {
case err == nil:
ctx.Redirect(http.StatusFound, target)
return
case errors.Is(err, app.ErrNotFound):
ctx.Status(404)
return
default:
_ = ctx.AbortWithError(http.StatusInternalServerError, err)
}
}
func (s *Server) SavePURL(ctx *gin.Context) {
domain := ctx.Param("domain")
name := ctx.Param("name")
var req res.SavePURL
if err := ctx.BindJSON(&req); err != nil {
ctx.Abort()
return
}
err := s.service.SavePURL(domain, name, req.Target)
switch true {
case err == nil:
ctx.Status(http.StatusNoContent)
return
default:
_ = ctx.Error(err)
ctx.Abort()
}
}
func (s *Server) CreateDomain(ctx *gin.Context) {
domain := ctx.Param("domain")
err := s.service.CreateDomain(domain)
switch true {
case err == nil:
ctx.Status(http.StatusNoContent)
return
case errors.Is(err, app.ErrBadRequest):
ctx.Status(http.StatusBadRequest)
return
default:
_ = ctx.AbortWithError(http.StatusInternalServerError, err)
return
}
}