web.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package cmd
  5. import (
  6. "crypto/tls"
  7. "fmt"
  8. "html/template"
  9. "io/ioutil"
  10. "net/http"
  11. "net/http/fcgi"
  12. "os"
  13. "os/signal"
  14. "path"
  15. "strings"
  16. "github.com/Unknwon/macaron"
  17. "github.com/codegangsta/cli"
  18. "github.com/go-xorm/xorm"
  19. "github.com/macaron-contrib/binding"
  20. "github.com/macaron-contrib/cache"
  21. "github.com/macaron-contrib/captcha"
  22. "github.com/macaron-contrib/csrf"
  23. "github.com/macaron-contrib/i18n"
  24. "github.com/macaron-contrib/oauth2"
  25. "github.com/macaron-contrib/session"
  26. "github.com/macaron-contrib/toolbox"
  27. "github.com/mcuadros/go-version"
  28. "gopkg.in/ini.v1"
  29. api "github.com/gogits/go-gogs-client"
  30. "github.com/gogits/gogs/models"
  31. "github.com/gogits/gogs/modules/auth"
  32. "github.com/gogits/gogs/modules/auth/apiv1"
  33. "github.com/gogits/gogs/modules/avatar"
  34. "github.com/gogits/gogs/modules/base"
  35. "github.com/gogits/gogs/modules/bindata"
  36. "github.com/gogits/gogs/modules/log"
  37. "github.com/gogits/gogs/modules/middleware"
  38. "github.com/gogits/gogs/modules/setting"
  39. "github.com/gogits/gogs/routers"
  40. "github.com/gogits/gogs/routers/admin"
  41. "github.com/gogits/gogs/routers/api/v1"
  42. "github.com/gogits/gogs/routers/dev"
  43. "github.com/gogits/gogs/routers/org"
  44. "github.com/gogits/gogs/routers/repo"
  45. "github.com/gogits/gogs/routers/user"
  46. )
  47. var CmdWeb = cli.Command{
  48. Name: "web",
  49. Usage: "Start Gogs web server",
  50. Description: `Gogs web server is the only thing you need to run,
  51. and it takes care of all the other things for you`,
  52. Action: runWeb,
  53. Flags: []cli.Flag{
  54. cli.StringFlag{"port, p", "3000", "Temporary port number to prevent conflict", ""},
  55. cli.StringFlag{"config, c", "custom/conf/app.ini", "Custom configuration file path", ""},
  56. },
  57. }
  58. type VerChecker struct {
  59. ImportPath string
  60. Version func() string
  61. Expected string
  62. }
  63. // checkVersion checks if binary matches the version of templates files.
  64. func checkVersion() {
  65. // Templates.
  66. data, err := ioutil.ReadFile(setting.StaticRootPath + "/templates/.VERSION")
  67. if err != nil {
  68. log.Fatal(4, "Fail to read 'templates/.VERSION': %v", err)
  69. }
  70. if string(data) != setting.AppVer {
  71. log.Fatal(4, "Binary and template file version does not match, did you forget to recompile?")
  72. }
  73. // Check dependency version.
  74. checkers := []VerChecker{
  75. {"github.com/go-xorm/xorm", func() string { return xorm.Version }, "0.4.3.0806"},
  76. {"github.com/Unknwon/macaron", macaron.Version, "0.5.4"},
  77. {"github.com/macaron-contrib/binding", binding.Version, "0.1.0"},
  78. {"github.com/macaron-contrib/cache", cache.Version, "0.0.7"},
  79. {"github.com/macaron-contrib/csrf", csrf.Version, "0.0.3"},
  80. {"github.com/macaron-contrib/i18n", i18n.Version, "0.0.7"},
  81. {"github.com/macaron-contrib/session", session.Version, "0.1.6"},
  82. {"gopkg.in/ini.v1", ini.Version, "1.3.4"},
  83. }
  84. for _, c := range checkers {
  85. if !version.Compare(c.Version(), c.Expected, ">=") {
  86. log.Fatal(4, "Package '%s' version is too old(%s -> %s), did you forget to update?", c.ImportPath, c.Version(), c.Expected)
  87. }
  88. }
  89. }
  90. // newMacaron initializes Macaron instance.
  91. func newMacaron() *macaron.Macaron {
  92. m := macaron.New()
  93. if !setting.DisableRouterLog {
  94. m.Use(macaron.Logger())
  95. }
  96. m.Use(macaron.Recovery())
  97. if setting.EnableGzip {
  98. m.Use(macaron.Gziper())
  99. }
  100. if setting.Protocol == setting.FCGI {
  101. m.SetURLPrefix(setting.AppSubUrl)
  102. }
  103. m.Use(macaron.Static(
  104. path.Join(setting.StaticRootPath, "public"),
  105. macaron.StaticOptions{
  106. SkipLogging: setting.DisableRouterLog,
  107. },
  108. ))
  109. m.Use(macaron.Static(
  110. setting.AvatarUploadPath,
  111. macaron.StaticOptions{
  112. Prefix: "avatars",
  113. SkipLogging: setting.DisableRouterLog,
  114. },
  115. ))
  116. m.Use(macaron.Renderer(macaron.RenderOptions{
  117. Directory: path.Join(setting.StaticRootPath, "templates"),
  118. Funcs: []template.FuncMap{base.TemplateFuncs},
  119. IndentJSON: macaron.Env != macaron.PROD,
  120. }))
  121. localeNames, err := bindata.AssetDir("conf/locale")
  122. if err != nil {
  123. log.Fatal(4, "Fail to list locale files: %v", err)
  124. }
  125. localFiles := make(map[string][]byte)
  126. for _, name := range localeNames {
  127. localFiles[name] = bindata.MustAsset("conf/locale/" + name)
  128. }
  129. m.Use(i18n.I18n(i18n.Options{
  130. SubURL: setting.AppSubUrl,
  131. Files: localFiles,
  132. CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
  133. Langs: setting.Langs,
  134. Names: setting.Names,
  135. Redirect: true,
  136. }))
  137. m.Use(cache.Cacher(cache.Options{
  138. Adapter: setting.CacheAdapter,
  139. AdapterConfig: setting.CacheConn,
  140. Interval: setting.CacheInternal,
  141. }))
  142. m.Use(captcha.Captchaer(captcha.Options{
  143. SubURL: setting.AppSubUrl,
  144. }))
  145. m.Use(session.Sessioner(setting.SessionConfig))
  146. m.Use(csrf.Csrfer(csrf.Options{
  147. Secret: setting.SecretKey,
  148. SetCookie: true,
  149. Header: "X-Csrf-Token",
  150. CookiePath: setting.AppSubUrl,
  151. }))
  152. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  153. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  154. &toolbox.HealthCheckFuncDesc{
  155. Desc: "Database connection",
  156. Func: models.Ping,
  157. },
  158. },
  159. }))
  160. // OAuth 2.
  161. if setting.OauthService != nil {
  162. for _, info := range setting.OauthService.OauthInfos {
  163. m.Use(oauth2.NewOAuth2Provider(info.Options, info.AuthUrl, info.TokenUrl))
  164. }
  165. }
  166. m.Use(middleware.Contexter())
  167. return m
  168. }
  169. func runWeb(ctx *cli.Context) {
  170. if ctx.IsSet("config") {
  171. setting.CustomConf = ctx.String("config")
  172. }
  173. routers.GlobalInit()
  174. checkVersion()
  175. m := newMacaron()
  176. reqSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true})
  177. ignSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: setting.Service.RequireSignInView})
  178. ignSignInAndCsrf := middleware.Toggle(&middleware.ToggleOptions{DisableCsrf: true})
  179. reqSignOut := middleware.Toggle(&middleware.ToggleOptions{SignOutRequire: true})
  180. bind := binding.Bind
  181. bindIgnErr := binding.BindIgnErr
  182. // Routers.
  183. m.Get("/", ignSignIn, routers.Home)
  184. m.Get("/explore", ignSignIn, routers.Explore)
  185. m.Combo("/install", routers.InstallInit).
  186. Get(routers.Install).
  187. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  188. m.Group("", func() {
  189. m.Get("/pulls", user.Pulls)
  190. m.Get("/issues", user.Issues)
  191. }, reqSignIn)
  192. // API.
  193. // FIXME: custom form error response.
  194. m.Group("/api", func() {
  195. m.Group("/v1", func() {
  196. // Miscellaneous.
  197. m.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown)
  198. m.Post("/markdown/raw", v1.MarkdownRaw)
  199. // Users.
  200. m.Group("/users", func() {
  201. m.Get("/search", v1.SearchUsers)
  202. m.Group("/:username", func() {
  203. m.Get("", v1.GetUserInfo)
  204. m.Group("/tokens", func() {
  205. m.Combo("").Get(v1.ListAccessTokens).Post(bind(v1.CreateAccessTokenForm{}), v1.CreateAccessToken)
  206. }, middleware.ApiReqBasicAuth())
  207. })
  208. })
  209. // Repositories.
  210. m.Combo("/user/repos", middleware.ApiReqToken()).Get(v1.ListMyRepos).
  211. Post(bind(api.CreateRepoOption{}), v1.CreateRepo)
  212. m.Post("/org/:org/repos", middleware.ApiReqToken(), bind(api.CreateRepoOption{}), v1.CreateOrgRepo)
  213. m.Group("/repos", func() {
  214. m.Get("/search", v1.SearchRepos)
  215. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), v1.MigrateRepo)
  216. m.Group("/:username/:reponame", func() {
  217. m.Combo("/hooks").Get(v1.ListRepoHooks).
  218. Post(bind(api.CreateHookOption{}), v1.CreateRepoHook)
  219. m.Patch("/hooks/:id:int", bind(api.EditHookOption{}), v1.EditRepoHook)
  220. m.Get("/raw/*", middleware.RepoRef(), v1.GetRepoRawFile)
  221. }, middleware.ApiRepoAssignment(), middleware.ApiReqToken())
  222. })
  223. m.Any("/*", func(ctx *middleware.Context) {
  224. ctx.HandleAPI(404, "Page not found")
  225. })
  226. })
  227. }, ignSignIn)
  228. // User.
  229. m.Group("/user", func() {
  230. m.Get("/login", user.SignIn)
  231. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  232. m.Get("/info/:name", user.SocialSignIn)
  233. m.Get("/sign_up", user.SignUp)
  234. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  235. m.Get("/reset_password", user.ResetPasswd)
  236. m.Post("/reset_password", user.ResetPasswdPost)
  237. }, reqSignOut)
  238. m.Group("/user/settings", func() {
  239. m.Get("", user.Settings)
  240. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  241. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), user.SettingsAvatar)
  242. m.Get("/email", user.SettingsEmails)
  243. m.Post("/email", bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  244. m.Get("/password", user.SettingsPassword)
  245. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  246. m.Get("/ssh", user.SettingsSSHKeys)
  247. m.Post("/ssh", bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  248. m.Get("/social", user.SettingsSocial)
  249. m.Combo("/applications").Get(user.SettingsApplications).Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  250. m.Route("/delete", "GET,POST", user.SettingsDelete)
  251. }, reqSignIn)
  252. m.Group("/user", func() {
  253. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  254. m.Any("/activate", user.Activate)
  255. m.Any("/activate_email", user.ActivateEmail)
  256. m.Get("/email2user", user.Email2User)
  257. m.Get("/forget_password", user.ForgotPasswd)
  258. m.Post("/forget_password", user.ForgotPasswdPost)
  259. m.Get("/logout", user.SignOut)
  260. })
  261. // Gravatar service.
  262. avt := avatar.CacheServer("public/img/avatar/", "public/img/avatar_default.jpg")
  263. os.MkdirAll("public/img/avatar/", os.ModePerm)
  264. m.Get("/avatar/:hash", avt.ServeHTTP)
  265. adminReq := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true, AdminRequire: true})
  266. m.Group("/admin", func() {
  267. m.Get("", adminReq, admin.Dashboard)
  268. m.Get("/config", admin.Config)
  269. m.Get("/monitor", admin.Monitor)
  270. m.Group("/users", func() {
  271. m.Get("", admin.Users)
  272. m.Get("/new", admin.NewUser)
  273. m.Post("/new", bindIgnErr(auth.RegisterForm{}), admin.NewUserPost)
  274. m.Get("/:userid", admin.EditUser)
  275. m.Post("/:userid", bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  276. m.Post("/:userid/delete", admin.DeleteUser)
  277. })
  278. m.Group("/orgs", func() {
  279. m.Get("", admin.Organizations)
  280. })
  281. m.Group("/repos", func() {
  282. m.Get("", admin.Repositories)
  283. })
  284. m.Group("/auths", func() {
  285. m.Get("", admin.Authentications)
  286. m.Get("/new", admin.NewAuthSource)
  287. m.Post("/new", bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  288. m.Get("/:authid", admin.EditAuthSource)
  289. m.Post("/:authid", bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  290. m.Post("/:authid/delete", admin.DeleteAuthSource)
  291. })
  292. m.Group("/notices", func() {
  293. m.Get("", admin.Notices)
  294. m.Get("/:id:int/delete", admin.DeleteNotice)
  295. })
  296. }, adminReq)
  297. m.Group("", func() {
  298. m.Get("/:username", user.Profile)
  299. m.Get("/attachments/:uuid", func(ctx *middleware.Context) {
  300. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  301. if err != nil {
  302. if models.IsErrAttachmentNotExist(err) {
  303. ctx.Error(404)
  304. } else {
  305. ctx.Handle(500, "GetAttachmentByUUID", err)
  306. }
  307. return
  308. }
  309. fr, err := os.Open(attach.LocalPath())
  310. if err != nil {
  311. ctx.Handle(500, "Open", err)
  312. return
  313. }
  314. defer fr.Close()
  315. ctx.Header().Set("Cache-Control", "public,max-age=86400")
  316. // Fix #312. Attachments with , in their name are not handled correctly by Google Chrome.
  317. // We must put the name in " manually.
  318. if err = repo.ServeData(ctx, "\""+attach.Name+"\"", fr); err != nil {
  319. ctx.Handle(500, "ServeData", err)
  320. return
  321. }
  322. })
  323. m.Post("/issues/attachments", repo.UploadIssueAttachment)
  324. }, ignSignIn)
  325. if macaron.Env == macaron.DEV {
  326. m.Get("/template/*", dev.TemplatePreview)
  327. }
  328. reqRepoAdmin := middleware.RequireRepoAdmin()
  329. // Organization.
  330. m.Group("/org", func() {
  331. m.Get("/create", org.Create)
  332. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  333. m.Group("/:org", func() {
  334. m.Get("/dashboard", user.Dashboard)
  335. m.Get("/members", org.Members)
  336. m.Get("/members/action/:action", org.MembersAction)
  337. m.Get("/teams", org.Teams)
  338. m.Get("/teams/:team", org.TeamMembers)
  339. m.Get("/teams/:team/repositories", org.TeamRepositories)
  340. m.Get("/teams/:team/action/:action", org.TeamsAction)
  341. m.Get("/teams/:team/action/repo/:action", org.TeamsRepoAction)
  342. }, middleware.OrgAssignment(true, true))
  343. m.Group("/:org", func() {
  344. m.Get("/teams/new", org.NewTeam)
  345. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  346. m.Get("/teams/:team/edit", org.EditTeam)
  347. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  348. m.Post("/teams/:team/delete", org.DeleteTeam)
  349. m.Group("/settings", func() {
  350. m.Get("", org.Settings)
  351. m.Post("", bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  352. m.Get("/hooks", org.SettingsHooks)
  353. m.Get("/hooks/new", repo.WebHooksNew)
  354. m.Post("/hooks/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  355. m.Post("/hooks/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  356. m.Get("/hooks/:id", repo.WebHooksEdit)
  357. m.Post("/hooks/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  358. m.Post("/hooks/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  359. m.Route("/delete", "GET,POST", org.SettingsDelete)
  360. })
  361. m.Route("/invitations/new", "GET,POST", org.Invitation)
  362. }, middleware.OrgAssignment(true, true, true))
  363. }, reqSignIn)
  364. m.Group("/org", func() {
  365. m.Get("/:org", org.Home)
  366. }, ignSignIn, middleware.OrgAssignment(true))
  367. // Repository.
  368. m.Group("/repo", func() {
  369. m.Get("/create", repo.Create)
  370. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  371. m.Get("/migrate", repo.Migrate)
  372. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  373. m.Combo("/fork/:repoid").Get(repo.Fork).
  374. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  375. }, reqSignIn)
  376. m.Group("/:username/:reponame", func() {
  377. m.Get("/settings", repo.Settings)
  378. m.Post("/settings", bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  379. m.Group("/settings", func() {
  380. m.Route("/collaboration", "GET,POST", repo.SettingsCollaboration)
  381. m.Get("/hooks", repo.Webhooks)
  382. m.Get("/hooks/new", repo.WebHooksNew)
  383. m.Post("/hooks/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  384. m.Post("/hooks/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  385. m.Get("/hooks/:id", repo.WebHooksEdit)
  386. m.Post("/hooks/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  387. m.Post("/hooks/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  388. m.Group("/hooks/git", func() {
  389. m.Get("", repo.GitHooks)
  390. m.Get("/:name", repo.GitHooksEdit)
  391. m.Post("/:name", repo.GitHooksEditPost)
  392. }, middleware.GitHookService())
  393. m.Group("/keys", func() {
  394. m.Combo("").Get(repo.SettingsDeployKeys).
  395. Post(bindIgnErr(auth.AddSSHKeyForm{}), repo.SettingsDeployKeysPost)
  396. m.Post("/delete", repo.DeleteDeployKey)
  397. })
  398. })
  399. }, reqSignIn, middleware.RepoAssignment(true), reqRepoAdmin)
  400. m.Group("/:username/:reponame", func() {
  401. m.Get("/action/:action", repo.Action)
  402. m.Group("/issues", func() {
  403. m.Combo("/new").Get(repo.NewIssue).
  404. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  405. m.Combo("/:index/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  406. m.Group("/:index", func() {
  407. m.Post("", bindIgnErr(auth.CreateIssueForm{}), repo.UpdateIssue)
  408. m.Post("/label", repo.UpdateIssueLabel)
  409. m.Post("/milestone", repo.UpdateIssueMilestone)
  410. m.Post("/assignee", repo.UpdateIssueAssignee)
  411. }, reqRepoAdmin)
  412. })
  413. m.Group("/labels", func() {
  414. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  415. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  416. m.Post("/delete", repo.DeleteLabel)
  417. }, reqRepoAdmin)
  418. m.Group("/milestones", func() {
  419. m.Get("/new", repo.NewMilestone)
  420. m.Post("/new", bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  421. m.Get("/:id/edit", repo.EditMilestone)
  422. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  423. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  424. m.Post("/delete", repo.DeleteMilestone)
  425. }, reqRepoAdmin)
  426. m.Group("/releases", func() {
  427. m.Get("/new", repo.NewRelease)
  428. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  429. m.Get("/edit/:tagname", repo.EditRelease)
  430. m.Post("/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  431. }, reqRepoAdmin, middleware.RepoRef())
  432. m.Combo("/compare/*").Get(repo.CompareAndPullRequest)
  433. }, reqSignIn, middleware.RepoAssignment(true))
  434. m.Group("/:username/:reponame", func() {
  435. m.Get("/releases", middleware.RepoRef(), repo.Releases)
  436. m.Get("/issues", repo.RetrieveLabels, repo.Issues)
  437. m.Get("/issues/:index", repo.ViewIssue)
  438. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  439. m.Get("/milestones", repo.Milestones)
  440. m.Get("/pulls", repo.Pulls)
  441. m.Get("/branches", repo.Branches)
  442. m.Get("/archive/*", repo.Download)
  443. m.Get("/pulls2/", repo.PullRequest2)
  444. m.Group("", func() {
  445. m.Get("/src/*", repo.Home)
  446. m.Get("/raw/*", repo.SingleDownload)
  447. m.Get("/commits/*", repo.RefCommits)
  448. m.Get("/commit/*", repo.Diff)
  449. }, middleware.RepoRef())
  450. m.Get("/compare/:before([a-z0-9]{40})...:after([a-z0-9]{40})", repo.CompareDiff)
  451. }, ignSignIn, middleware.RepoAssignment(true))
  452. m.Group("/:username", func() {
  453. m.Group("/:reponame", func() {
  454. m.Get("", repo.Home)
  455. m.Get(".git", repo.Home)
  456. }, ignSignIn, middleware.RepoAssignment(true, true), middleware.RepoRef())
  457. m.Group("/:reponame", func() {
  458. m.Any("/*", ignSignInAndCsrf, repo.Http)
  459. m.Head("/hooks/trigger", repo.TriggerHook)
  460. })
  461. })
  462. // robots.txt
  463. m.Get("/robots.txt", func(ctx *middleware.Context) {
  464. if setting.HasRobotsTxt {
  465. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  466. } else {
  467. ctx.Error(404)
  468. }
  469. })
  470. // Not found handler.
  471. m.NotFound(routers.NotFound)
  472. // Detect kill signal.
  473. c := make(chan os.Signal, 1)
  474. signal.Notify(c, os.Interrupt)
  475. go func() {
  476. for _ = range c {
  477. fmt.Println("Kill signal detected, exiting now...")
  478. os.Exit(0)
  479. }
  480. }()
  481. // Flag for port number in case first time run conflict.
  482. if ctx.IsSet("port") {
  483. setting.AppUrl = strings.Replace(setting.AppUrl, setting.HttpPort, ctx.String("port"), 1)
  484. setting.HttpPort = ctx.String("port")
  485. }
  486. var err error
  487. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  488. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  489. switch setting.Protocol {
  490. case setting.HTTP:
  491. err = http.ListenAndServe(listenAddr, m)
  492. case setting.HTTPS:
  493. server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS10}, Handler: m}
  494. err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  495. case setting.FCGI:
  496. err = fcgi.Serve(nil, m)
  497. default:
  498. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  499. }
  500. if err != nil {
  501. log.Fatal(4, "Fail to start server: %v", err)
  502. }
  503. }