forked from gravitypriest/cat-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcat-server.go
68 lines (57 loc) · 1.57 KB
/
cat-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
package main
import (
"net/http"
"regexp"
"github.com/labstack/echo"
"github.com/labstack/echo/engine/standard"
"github.com/labstack/echo/middleware"
)
type Cat struct {
Message string `json:"message"`
Position string `json:"position"`
Picture string `json:"picture"`
}
func sendResponse(ctx echo.Context) error {
cat := new(Cat)
cat.Message = ""
cat.Position = ""
cat.Picture = ""
params := ctx.ParamNames()
for _, p := range params {
switch p {
case "message":
cat.Message = ctx.Param(p)
case "position":
cat.Position = ctx.Param(p)
case "picture":
cat.Picture = ctx.Param(p)
default:
}
}
return ctx.JSON(http.StatusOK, cat)
}
func unfuckPath() echo.MiddlewareFunc {
// remove duplicate slashes
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(ctx echo.Context) error {
req := ctx.Request()
url := req.URL()
path := url.Path()
reg, _ := regexp.Compile("(/+)")
path = reg.ReplaceAllString(path, "/")
req.SetURI(path)
url.SetPath(path)
return next(ctx)
}
}
}
func main() {
srv := echo.New()
srv.Pre(unfuckPath())
srv.Pre(middleware.RemoveTrailingSlash())
srv.GET("/", sendResponse)
srv.GET("/:message", sendResponse)
srv.GET("/:message/:position", sendResponse)
srv.GET("/:message/:position/:picture", sendResponse)
srv.Run(standard.New(":8080"))
}