forked from kevincobain2000/cache-http
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
177 lines (152 loc) · 4 KB
/
main.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package main
import (
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/fvbock/endless"
"github.com/joho/godotenv"
echo "github.com/labstack/echo/v4"
middleware "github.com/labstack/echo/v4/middleware"
)
// successResponse ...
type successResponse struct {
Status bool `json:"status"`
}
const assetsPath = "assets/"
type Params struct {
Host string `json:"host"`
Port string `json:"port"`
PidDir string `json:"pid"`
}
func main() {
e := echo.New()
loadEnv()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Use(touch())
if os.Getenv("USERNAME") != "" && os.Getenv("PASSWORD") != "" {
basicAuth(e)
}
e.GET("/health", health)
e.Static("/assets", assetsPath)
e.POST("/upload", upload)
params := cliParams()
serveGracefully(e, params.Host, params.Port, params.PidDir)
}
//named paramters
func cliParams() Params {
params := Params{
Host: "localhost",
Port: "3000",
PidDir: "./",
}
//go run main.go -host=localhost -port=3000 -pidDir=./
for _, arg := range os.Args {
if strings.HasPrefix(arg, "-host=") || strings.HasPrefix(arg, "--host=") {
params.Host = strings.ReplaceAll(arg, "-host=", "")
params.Host = strings.ReplaceAll(arg, "--host=", "")
}
if strings.HasPrefix(arg, "-port=") || strings.HasPrefix(arg, "--port=") {
params.Port = strings.ReplaceAll(arg, "--port=", "")
}
if strings.HasPrefix(arg, "-pidDir=") || strings.HasPrefix(arg, "--pidDir=") {
params.PidDir = strings.ReplaceAll(arg, "--pidDir=", "")
}
}
return params
}
func touch() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
req := c.Request()
uri := req.RequestURI
if strings.HasPrefix(uri, "/assets/") == true {
filename := strings.ReplaceAll(uri, "/assets/", "")
currenttime := time.Now().Local()
err := os.Chtimes(assetsPath+filename, currenttime, currenttime)
if err != nil {
log.Println(err)
}
}
err := next(c)
if err != nil {
return err
}
return nil
}
}
}
func basicAuth(e *echo.Echo) {
e.Use(middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
if username == os.Getenv("USERNAME") && password == os.Getenv("PASSWORD") {
return true, nil
}
return false, nil
}))
}
func serveGracefully(e *echo.Echo, host string, port, pidDir string) {
e.Server.Addr = host + ":" + port
server := endless.NewServer(e.Server.Addr, e)
server.BeforeBegin = func(add string) {
log.Print("info: actual pid is", syscall.Getpid())
pidFile := filepath.Join(pidDir, port+".pid")
err := os.Remove(pidFile)
if err != nil {
log.Print("error: pid file error: ", err)
} else {
log.Print("success: pid file success: ", pidFile)
}
err = ioutil.WriteFile(pidFile, []byte(strconv.Itoa(os.Getpid())), 0644)
if err != nil {
log.Print("error: write pid file error: ", err)
} else {
log.Print("success: write pid file success: ", pidFile)
}
}
if err := server.ListenAndServe(); err != nil {
log.Print("critical: graceful error: ", err)
}
}
func loadEnv() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
}
func health(c echo.Context) error {
return c.JSON(http.StatusOK, &successResponse{Status: true})
}
func upload(c echo.Context) error {
//-----------
// Read file
//-----------
// Source
file, err := c.FormFile("file")
if err != nil {
log.Print(err.Error())
return err
}
src, err := file.Open()
if err != nil {
return err
}
defer src.Close()
// Destination
dst, err := os.Create(assetsPath + file.Filename)
if err != nil {
return err
}
defer dst.Close()
// Copy
if _, err = io.Copy(dst, src); err != nil {
return err
}
return c.JSON(http.StatusOK, &successResponse{Status: true})
}