-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
227 lines (194 loc) · 6.74 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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package main
// ISUCON的な参考: https://github.com/isucon/isucon12-qualify/blob/main/webapp/go/isuports.go#L336
// sqlx的な参考: https://jmoiron.github.io/sqlx/
import (
"fmt"
"log"
"net"
"net/http"
"os"
"os/exec"
"strconv"
"github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
echolog "github.com/labstack/gommon/log"
)
const (
listenPort = 8080
powerDNSSubdomainAddressEnvKey = "ISUCON13_POWERDNS_SUBDOMAIN_ADDRESS"
)
var (
powerDNSSubdomainAddress string
dbConn *sqlx.DB
secret = []byte("isucon13_session_cookiestore_defaultsecret")
)
func init() {
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
if secretKey, ok := os.LookupEnv("ISUCON13_SESSION_SECRETKEY"); ok {
secret = []byte(secretKey)
}
}
type InitializeResponse struct {
Language string `json:"language"`
}
func connectDB(logger echo.Logger) (*sqlx.DB, error) {
const (
networkTypeEnvKey = "ISUCON13_MYSQL_DIALCONFIG_NET"
addrEnvKey = "ISUCON13_MYSQL_DIALCONFIG_ADDRESS"
portEnvKey = "ISUCON13_MYSQL_DIALCONFIG_PORT"
userEnvKey = "ISUCON13_MYSQL_DIALCONFIG_USER"
passwordEnvKey = "ISUCON13_MYSQL_DIALCONFIG_PASSWORD"
dbNameEnvKey = "ISUCON13_MYSQL_DIALCONFIG_DATABASE"
parseTimeEnvKey = "ISUCON13_MYSQL_DIALCONFIG_PARSETIME"
)
conf := mysql.NewConfig()
// 環境変数がセットされていなかった場合でも一旦動かせるように、デフォルト値を入れておく
// この挙動を変更して、エラーを出すようにしてもいいかもしれない
conf.Net = "tcp"
conf.Addr = net.JoinHostPort("127.0.0.1", "3306")
conf.User = "isucon"
conf.Passwd = "isucon"
conf.DBName = "isupipe"
conf.ParseTime = true
if v, ok := os.LookupEnv(networkTypeEnvKey); ok {
conf.Net = v
}
if addr, ok := os.LookupEnv(addrEnvKey); ok {
if port, ok2 := os.LookupEnv(portEnvKey); ok2 {
conf.Addr = net.JoinHostPort(addr, port)
} else {
conf.Addr = net.JoinHostPort(addr, "3306")
}
}
if v, ok := os.LookupEnv(userEnvKey); ok {
conf.User = v
}
if v, ok := os.LookupEnv(passwordEnvKey); ok {
conf.Passwd = v
}
if v, ok := os.LookupEnv(dbNameEnvKey); ok {
conf.DBName = v
}
if v, ok := os.LookupEnv(parseTimeEnvKey); ok {
parseTime, err := strconv.ParseBool(v)
if err != nil {
return nil, fmt.Errorf("failed to parse environment variable '%s' as bool: %+v", parseTimeEnvKey, err)
}
conf.ParseTime = parseTime
}
db, err := sqlx.Open("mysql", conf.FormatDSN())
if err != nil {
return nil, err
}
db.SetMaxOpenConns(10)
if err := db.Ping(); err != nil {
return nil, err
}
return db, nil
}
func initializeHandler(c echo.Context) error {
if out, err := exec.Command("../sql/init.sh").CombinedOutput(); err != nil {
c.Logger().Warnf("init.sh failed with err=%s", string(out))
return echo.NewHTTPError(http.StatusInternalServerError, "failed to initialize: "+err.Error())
}
c.Request().Header.Add("Content-Type", "application/json;charset=utf-8")
return c.JSON(http.StatusOK, InitializeResponse{
Language: "golang",
})
}
func main() {
e := echo.New()
e.Debug = true
e.Logger.SetLevel(echolog.DEBUG)
e.Use(middleware.Logger())
cookieStore := sessions.NewCookieStore(secret)
cookieStore.Options.Domain = "*.u.isucon.local"
e.Use(session.Middleware(cookieStore))
// e.Use(middleware.Recover())
// 初期化
e.POST("/api/initialize", initializeHandler)
// top
e.GET("/api/tag", getTagHandler)
e.GET("/api/user/:username/theme", getStreamerThemeHandler)
// livestream
// reserve livestream
e.POST("/api/livestream/reservation", reserveLivestreamHandler)
// list livestream
e.GET("/api/livestream/search", searchLivestreamsHandler)
e.GET("/api/livestream", getMyLivestreamsHandler)
e.GET("/api/user/:username/livestream", getUserLivestreamsHandler)
// get livestream
e.GET("/api/livestream/:livestream_id", getLivestreamHandler)
// get polling livecomment timeline
e.GET("/api/livestream/:livestream_id/livecomment", getLivecommentsHandler)
// ライブコメント投稿
e.POST("/api/livestream/:livestream_id/livecomment", postLivecommentHandler)
e.POST("/api/livestream/:livestream_id/reaction", postReactionHandler)
e.GET("/api/livestream/:livestream_id/reaction", getReactionsHandler)
// (配信者向け)ライブコメントの報告一覧取得API
e.GET("/api/livestream/:livestream_id/report", getLivecommentReportsHandler)
e.GET("/api/livestream/:livestream_id/ngwords", getNgwords)
// ライブコメント報告
e.POST("/api/livestream/:livestream_id/livecomment/:livecomment_id/report", reportLivecommentHandler)
// 配信者によるモデレーション (NGワード登録)
e.POST("/api/livestream/:livestream_id/moderate", moderateHandler)
// livestream_viewersにINSERTするため必要
// ユーザ視聴開始 (viewer)
e.POST("/api/livestream/:livestream_id/enter", enterLivestreamHandler)
// ユーザ視聴終了 (viewer)
e.DELETE("/api/livestream/:livestream_id/exit", exitLivestreamHandler)
// user
e.POST("/api/register", registerHandler)
e.POST("/api/login", loginHandler)
e.GET("/api/user/me", getMeHandler)
// フロントエンドで、配信予約のコラボレーターを指定する際に必要
e.GET("/api/user/:username", getUserHandler)
e.GET("/api/user/:username/statistics", getUserStatisticsHandler)
e.GET("/api/user/:username/icon", getIconHandler)
e.POST("/api/icon", postIconHandler)
// stats
// ライブ配信統計情報
e.GET("/api/livestream/:livestream_id/statistics", getLivestreamStatisticsHandler)
// 課金情報
e.GET("/api/payment", GetPaymentResult)
e.HTTPErrorHandler = errorResponseHandler
// DB接続
conn, err := connectDB(e.Logger)
if err != nil {
e.Logger.Errorf("failed to connect db: %v", err)
os.Exit(1)
}
defer conn.Close()
dbConn = conn
subdomainAddr, ok := os.LookupEnv(powerDNSSubdomainAddressEnvKey)
if !ok {
e.Logger.Errorf("environ %s must be provided", powerDNSSubdomainAddressEnvKey)
os.Exit(1)
}
powerDNSSubdomainAddress = subdomainAddr
// HTTPサーバ起動
listenAddr := net.JoinHostPort("", strconv.Itoa(listenPort))
if err := e.Start(listenAddr); err != nil {
e.Logger.Errorf("failed to start HTTP server: %v", err)
os.Exit(1)
}
}
type ErrorResponse struct {
Error string `json:"error"`
}
func errorResponseHandler(err error, c echo.Context) {
c.Logger().Errorf("error at %s: %+v", c.Path(), err)
if he, ok := err.(*echo.HTTPError); ok {
if e := c.JSON(he.Code, &ErrorResponse{Error: err.Error()}); e != nil {
c.Logger().Errorf("%+v", e)
}
return
}
if e := c.JSON(http.StatusInternalServerError, &ErrorResponse{Error: err.Error()}); e != nil {
c.Logger().Errorf("%+v", e)
}
}