You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

572 lines
19 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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. gotmpl "html/template"
  9. "io/ioutil"
  10. "net/http"
  11. "net/http/fcgi"
  12. "os"
  13. "path"
  14. "strings"
  15. "github.com/codegangsta/cli"
  16. "github.com/go-macaron/binding"
  17. "github.com/go-macaron/cache"
  18. "github.com/go-macaron/captcha"
  19. "github.com/go-macaron/csrf"
  20. "github.com/go-macaron/gzip"
  21. "github.com/go-macaron/i18n"
  22. "github.com/go-macaron/session"
  23. "github.com/go-macaron/toolbox"
  24. "github.com/go-xorm/xorm"
  25. "github.com/mcuadros/go-version"
  26. "gopkg.in/ini.v1"
  27. "gopkg.in/macaron.v1"
  28. "github.com/gogits/git-module"
  29. "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/bindata"
  33. "github.com/gogits/gogs/modules/log"
  34. "github.com/gogits/gogs/modules/middleware"
  35. "github.com/gogits/gogs/modules/setting"
  36. "github.com/gogits/gogs/modules/template"
  37. "github.com/gogits/gogs/routers"
  38. "github.com/gogits/gogs/routers/admin"
  39. apiv1 "github.com/gogits/gogs/routers/api/v1"
  40. "github.com/gogits/gogs/routers/dev"
  41. "github.com/gogits/gogs/routers/org"
  42. "github.com/gogits/gogs/routers/repo"
  43. "github.com/gogits/gogs/routers/user"
  44. )
  45. var CmdWeb = cli.Command{
  46. Name: "web",
  47. Usage: "Start Gogs web server",
  48. Description: `Gogs web server is the only thing you need to run,
  49. and it takes care of all the other things for you`,
  50. Action: runWeb,
  51. Flags: []cli.Flag{
  52. stringFlag("port, p", "3000", "Temporary port number to prevent conflict"),
  53. stringFlag("config, c", "custom/conf/app.ini", "Custom configuration file path"),
  54. },
  55. }
  56. type VerChecker struct {
  57. ImportPath string
  58. Version func() string
  59. Expected string
  60. }
  61. // checkVersion checks if binary matches the version of templates files.
  62. func checkVersion() {
  63. // Templates.
  64. data, err := ioutil.ReadFile(setting.StaticRootPath + "/templates/.VERSION")
  65. if err != nil {
  66. log.Fatal(4, "Fail to read 'templates/.VERSION': %v", err)
  67. }
  68. if string(data) != setting.AppVer {
  69. log.Fatal(4, "Binary and template file version does not match, did you forget to recompile?")
  70. }
  71. // Check dependency version.
  72. checkers := []VerChecker{
  73. {"github.com/go-xorm/xorm", func() string { return xorm.Version }, "0.4.4.1029"},
  74. {"github.com/go-macaron/binding", binding.Version, "0.2.1"},
  75. {"github.com/go-macaron/cache", cache.Version, "0.1.2"},
  76. {"github.com/go-macaron/csrf", csrf.Version, "0.0.3"},
  77. {"github.com/go-macaron/i18n", i18n.Version, "0.2.0"},
  78. {"github.com/go-macaron/session", session.Version, "0.1.6"},
  79. {"github.com/go-macaron/toolbox", toolbox.Version, "0.1.0"},
  80. {"gopkg.in/ini.v1", ini.Version, "1.8.4"},
  81. {"gopkg.in/macaron.v1", macaron.Version, "0.8.0"},
  82. {"github.com/gogits/git-module", git.Version, "0.2.5"},
  83. {"github.com/gogits/go-gogs-client", gogs.Version, "0.7.3"},
  84. }
  85. for _, c := range checkers {
  86. if !version.Compare(c.Version(), c.Expected, ">=") {
  87. log.Fatal(4, "Package '%s' version is too old (%s -> %s), did you forget to update?", c.ImportPath, c.Version(), c.Expected)
  88. }
  89. }
  90. }
  91. // newMacaron initializes Macaron instance.
  92. func newMacaron() *macaron.Macaron {
  93. m := macaron.New()
  94. if !setting.DisableRouterLog {
  95. m.Use(macaron.Logger())
  96. }
  97. m.Use(macaron.Recovery())
  98. if setting.EnableGzip {
  99. m.Use(gzip.Gziper())
  100. }
  101. if setting.Protocol == setting.FCGI {
  102. m.SetURLPrefix(setting.AppSubUrl)
  103. }
  104. m.Use(macaron.Static(
  105. path.Join(setting.StaticRootPath, "public"),
  106. macaron.StaticOptions{
  107. SkipLogging: setting.DisableRouterLog,
  108. },
  109. ))
  110. m.Use(macaron.Static(
  111. setting.AvatarUploadPath,
  112. macaron.StaticOptions{
  113. Prefix: "avatars",
  114. SkipLogging: setting.DisableRouterLog,
  115. },
  116. ))
  117. m.Use(macaron.Renderer(macaron.RenderOptions{
  118. Directory: path.Join(setting.StaticRootPath, "templates"),
  119. Funcs: []gotmpl.FuncMap{template.Funcs},
  120. IndentJSON: macaron.Env != macaron.PROD,
  121. }))
  122. localeNames, err := bindata.AssetDir("conf/locale")
  123. if err != nil {
  124. log.Fatal(4, "Fail to list locale files: %v", err)
  125. }
  126. localFiles := make(map[string][]byte)
  127. for _, name := range localeNames {
  128. localFiles[name] = bindata.MustAsset("conf/locale/" + name)
  129. }
  130. m.Use(i18n.I18n(i18n.Options{
  131. SubURL: setting.AppSubUrl,
  132. Files: localFiles,
  133. CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
  134. Langs: setting.Langs,
  135. Names: setting.Names,
  136. DefaultLang: "en-US",
  137. Redirect: true,
  138. }))
  139. m.Use(cache.Cacher(cache.Options{
  140. Adapter: setting.CacheAdapter,
  141. AdapterConfig: setting.CacheConn,
  142. Interval: setting.CacheInternal,
  143. }))
  144. m.Use(captcha.Captchaer(captcha.Options{
  145. SubURL: setting.AppSubUrl,
  146. }))
  147. m.Use(session.Sessioner(setting.SessionConfig))
  148. m.Use(csrf.Csrfer(csrf.Options{
  149. Secret: setting.SecretKey,
  150. SetCookie: true,
  151. Header: "X-Csrf-Token",
  152. CookiePath: setting.AppSubUrl,
  153. }))
  154. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  155. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  156. &toolbox.HealthCheckFuncDesc{
  157. Desc: "Database connection",
  158. Func: models.Ping,
  159. },
  160. },
  161. }))
  162. m.Use(middleware.Contexter())
  163. return m
  164. }
  165. func runWeb(ctx *cli.Context) {
  166. if ctx.IsSet("config") {
  167. setting.CustomConf = ctx.String("config")
  168. }
  169. routers.GlobalInit()
  170. checkVersion()
  171. m := newMacaron()
  172. reqSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true})
  173. ignSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: setting.Service.RequireSignInView})
  174. ignSignInAndCsrf := middleware.Toggle(&middleware.ToggleOptions{DisableCsrf: true})
  175. reqSignOut := middleware.Toggle(&middleware.ToggleOptions{SignOutRequire: true})
  176. bindIgnErr := binding.BindIgnErr
  177. // Routers.
  178. m.Get("/", ignSignIn, routers.Home)
  179. m.Get("/explore", ignSignIn, routers.Explore)
  180. m.Combo("/install", routers.InstallInit).Get(routers.Install).
  181. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  182. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  183. // ***** START: API *****
  184. m.Group("/api", func() {
  185. apiv1.RegisterRoutes(m)
  186. }, ignSignIn)
  187. // ***** END: API *****
  188. // ***** START: User *****
  189. m.Group("/user", func() {
  190. m.Get("/login", user.SignIn)
  191. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  192. m.Get("/sign_up", user.SignUp)
  193. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  194. m.Get("/reset_password", user.ResetPasswd)
  195. m.Post("/reset_password", user.ResetPasswdPost)
  196. }, reqSignOut)
  197. m.Group("/user/settings", func() {
  198. m.Get("", user.Settings)
  199. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  200. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), user.SettingsAvatar)
  201. m.Combo("/email").Get(user.SettingsEmails).
  202. Post(bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  203. m.Post("/email/delete", user.DeleteEmail)
  204. m.Get("/password", user.SettingsPassword)
  205. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  206. m.Combo("/ssh").Get(user.SettingsSSHKeys).
  207. Post(bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  208. m.Post("/ssh/delete", user.DeleteSSHKey)
  209. m.Combo("/applications").Get(user.SettingsApplications).
  210. Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  211. m.Post("/applications/delete", user.SettingsDeleteApplication)
  212. m.Route("/delete", "GET,POST", user.SettingsDelete)
  213. }, reqSignIn, func(ctx *middleware.Context) {
  214. ctx.Data["PageIsUserSettings"] = true
  215. })
  216. m.Group("/user", func() {
  217. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  218. m.Any("/activate", user.Activate)
  219. m.Any("/activate_email", user.ActivateEmail)
  220. m.Get("/email2user", user.Email2User)
  221. m.Get("/forget_password", user.ForgotPasswd)
  222. m.Post("/forget_password", user.ForgotPasswdPost)
  223. m.Get("/logout", user.SignOut)
  224. })
  225. // ***** END: User *****
  226. adminReq := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true, AdminRequire: true})
  227. // ***** START: Admin *****
  228. m.Group("/admin", func() {
  229. m.Get("", adminReq, admin.Dashboard)
  230. m.Get("/config", admin.Config)
  231. m.Get("/monitor", admin.Monitor)
  232. m.Group("/users", func() {
  233. m.Get("", admin.Users)
  234. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCrateUserForm{}), admin.NewUserPost)
  235. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  236. m.Post("/:userid/delete", admin.DeleteUser)
  237. })
  238. m.Group("/orgs", func() {
  239. m.Get("", admin.Organizations)
  240. })
  241. m.Group("/repos", func() {
  242. m.Get("", admin.Repos)
  243. m.Post("/delete", admin.DeleteRepo)
  244. })
  245. m.Group("/auths", func() {
  246. m.Get("", admin.Authentications)
  247. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  248. m.Combo("/:authid").Get(admin.EditAuthSource).
  249. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  250. m.Post("/:authid/delete", admin.DeleteAuthSource)
  251. })
  252. m.Group("/notices", func() {
  253. m.Get("", admin.Notices)
  254. m.Post("/delete", admin.DeleteNotices)
  255. m.Get("/empty", admin.EmptyNotices)
  256. })
  257. }, adminReq)
  258. // ***** END: Admin *****
  259. m.Group("", func() {
  260. m.Group("/:username", func() {
  261. m.Get("", user.Profile)
  262. m.Get("/followers", user.Followers)
  263. m.Get("/following", user.Following)
  264. m.Get("/stars", user.Stars)
  265. })
  266. m.Get("/attachments/:uuid", func(ctx *middleware.Context) {
  267. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  268. if err != nil {
  269. if models.IsErrAttachmentNotExist(err) {
  270. ctx.Error(404)
  271. } else {
  272. ctx.Handle(500, "GetAttachmentByUUID", err)
  273. }
  274. return
  275. }
  276. fr, err := os.Open(attach.LocalPath())
  277. if err != nil {
  278. ctx.Handle(500, "Open", err)
  279. return
  280. }
  281. defer fr.Close()
  282. ctx.Header().Set("Cache-Control", "public,max-age=86400")
  283. // Fix #312. Attachments with , in their name are not handled correctly by Google Chrome.
  284. // We must put the name in " manually.
  285. if err = repo.ServeData(ctx, "\""+attach.Name+"\"", fr); err != nil {
  286. ctx.Handle(500, "ServeData", err)
  287. return
  288. }
  289. })
  290. m.Post("/issues/attachments", repo.UploadIssueAttachment)
  291. }, ignSignIn)
  292. m.Group("/:username", func() {
  293. m.Get("/action/:action", user.Action)
  294. }, reqSignIn)
  295. if macaron.Env == macaron.DEV {
  296. m.Get("/template/*", dev.TemplatePreview)
  297. }
  298. reqRepoAdmin := middleware.RequireRepoAdmin()
  299. reqRepoPusher := middleware.RequireRepoPusher()
  300. // ***** START: Organization *****
  301. m.Group("/org", func() {
  302. m.Get("/create", org.Create)
  303. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  304. m.Group("/:org", func() {
  305. m.Get("/dashboard", user.Dashboard)
  306. m.Get("/^:type(issues|pulls)$", user.Issues)
  307. m.Get("/members", org.Members)
  308. m.Get("/members/action/:action", org.MembersAction)
  309. m.Get("/teams", org.Teams)
  310. }, middleware.OrgAssignment(true))
  311. m.Group("/:org", func() {
  312. m.Get("/teams/:team", org.TeamMembers)
  313. m.Get("/teams/:team/repositories", org.TeamRepositories)
  314. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  315. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  316. }, middleware.OrgAssignment(true, false, true))
  317. m.Group("/:org", func() {
  318. m.Get("/teams/new", org.NewTeam)
  319. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  320. m.Get("/teams/:team/edit", org.EditTeam)
  321. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  322. m.Post("/teams/:team/delete", org.DeleteTeam)
  323. m.Group("/settings", func() {
  324. m.Combo("").Get(org.Settings).
  325. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  326. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), org.SettingsAvatar)
  327. m.Group("/hooks", func() {
  328. m.Get("", org.Webhooks)
  329. m.Post("/delete", org.DeleteWebhook)
  330. m.Get("/:type/new", repo.WebhooksNew)
  331. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  332. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  333. m.Get("/:id", repo.WebHooksEdit)
  334. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  335. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  336. })
  337. m.Route("/delete", "GET,POST", org.SettingsDelete)
  338. })
  339. m.Route("/invitations/new", "GET,POST", org.Invitation)
  340. }, middleware.OrgAssignment(true, true))
  341. }, reqSignIn)
  342. // ***** END: Organization *****
  343. // ***** START: Repository *****
  344. m.Group("/repo", func() {
  345. m.Get("/create", repo.Create)
  346. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  347. m.Get("/migrate", repo.Migrate)
  348. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  349. m.Combo("/fork/:repoid").Get(repo.Fork).
  350. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  351. }, reqSignIn)
  352. m.Group("/:username/:reponame", func() {
  353. m.Group("/settings", func() {
  354. m.Combo("").Get(repo.Settings).
  355. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  356. m.Route("/collaboration", "GET,POST", repo.Collaboration)
  357. m.Group("/hooks", func() {
  358. m.Get("", repo.Webhooks)
  359. m.Post("/delete", repo.DeleteWebhook)
  360. m.Get("/:type/new", repo.WebhooksNew)
  361. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  362. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  363. m.Get("/:id", repo.WebHooksEdit)
  364. m.Post("/:id/test", repo.TestWebhook)
  365. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  366. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  367. m.Group("/git", func() {
  368. m.Get("", repo.GitHooks)
  369. m.Combo("/:name").Get(repo.GitHooksEdit).
  370. Post(repo.GitHooksEditPost)
  371. }, middleware.GitHookService())
  372. })
  373. m.Group("/keys", func() {
  374. m.Combo("").Get(repo.DeployKeys).
  375. Post(bindIgnErr(auth.AddSSHKeyForm{}), repo.DeployKeysPost)
  376. m.Post("/delete", repo.DeleteDeployKey)
  377. })
  378. }, func(ctx *middleware.Context) {
  379. ctx.Data["PageIsSettings"] = true
  380. })
  381. }, reqSignIn, middleware.RepoAssignment(), reqRepoAdmin, middleware.RepoRef())
  382. m.Get("/:username/:reponame/action/:action", reqSignIn, middleware.RepoAssignment(), repo.Action)
  383. m.Group("/:username/:reponame", func() {
  384. m.Group("/issues", func() {
  385. m.Combo("/new", repo.MustEnableIssues).Get(middleware.RepoRef(), repo.NewIssue).
  386. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  387. m.Combo("/:index/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  388. m.Group("/:index", func() {
  389. m.Post("/label", repo.UpdateIssueLabel)
  390. m.Post("/milestone", repo.UpdateIssueMilestone)
  391. m.Post("/assignee", repo.UpdateIssueAssignee)
  392. }, reqRepoAdmin)
  393. m.Group("/:index", func() {
  394. m.Post("/title", repo.UpdateIssueTitle)
  395. m.Post("/content", repo.UpdateIssueContent)
  396. })
  397. })
  398. m.Post("/comments/:id", repo.UpdateCommentContent)
  399. m.Group("/labels", func() {
  400. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  401. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  402. m.Post("/delete", repo.DeleteLabel)
  403. }, reqRepoAdmin, middleware.RepoRef())
  404. m.Group("/milestones", func() {
  405. m.Combo("/new").Get(repo.NewMilestone).
  406. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  407. m.Get("/:id/edit", repo.EditMilestone)
  408. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  409. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  410. m.Post("/delete", repo.DeleteMilestone)
  411. }, reqRepoAdmin, middleware.RepoRef())
  412. m.Group("/releases", func() {
  413. m.Get("/new", repo.NewRelease)
  414. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  415. m.Get("/edit/:tagname", repo.EditRelease)
  416. m.Post("/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  417. m.Post("/delete", repo.DeleteRelease)
  418. }, reqRepoAdmin, middleware.RepoRef())
  419. m.Combo("/compare/*", repo.MustEnablePulls).Get(repo.CompareAndPullRequest).
  420. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  421. }, reqSignIn, middleware.RepoAssignment(), repo.MustBeNotBare)
  422. m.Group("/:username/:reponame", func() {
  423. m.Group("", func() {
  424. m.Get("/releases", repo.Releases)
  425. m.Get("/^:type(issues|pulls)$", repo.RetrieveLabels, repo.Issues)
  426. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  427. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  428. m.Get("/milestones", repo.Milestones)
  429. }, middleware.RepoRef())
  430. // m.Get("/branches", repo.Branches)
  431. m.Group("/wiki", func() {
  432. m.Get("/?:page", repo.Wiki)
  433. m.Get("/_pages", repo.WikiPages)
  434. m.Group("", func() {
  435. m.Combo("/_new").Get(repo.NewWiki).
  436. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  437. m.Combo("/:page/_edit").Get(repo.EditWiki).
  438. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  439. }, reqSignIn, reqRepoPusher)
  440. }, repo.MustEnableWiki, middleware.RepoRef())
  441. m.Get("/archive/*", repo.Download)
  442. m.Group("/pulls/:index", func() {
  443. m.Get("/commits", middleware.RepoRef(), repo.ViewPullCommits)
  444. m.Get("/files", middleware.RepoRef(), repo.ViewPullFiles)
  445. m.Post("/merge", reqRepoAdmin, repo.MergePullRequest)
  446. }, repo.MustEnablePulls)
  447. m.Group("", func() {
  448. m.Get("/src/*", repo.Home)
  449. m.Get("/raw/*", repo.SingleDownload)
  450. m.Get("/commits/*", repo.RefCommits)
  451. m.Get("/commit/*", repo.Diff)
  452. m.Get("/forks", repo.Forks)
  453. }, middleware.RepoRef())
  454. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.CompareDiff)
  455. }, ignSignIn, middleware.RepoAssignment(), repo.MustBeNotBare)
  456. m.Group("/:username/:reponame", func() {
  457. m.Get("/stars", repo.Stars)
  458. m.Get("/watchers", repo.Watchers)
  459. }, ignSignIn, middleware.RepoAssignment(), middleware.RepoRef())
  460. m.Group("/:username", func() {
  461. m.Group("/:reponame", func() {
  462. m.Get("", repo.Home)
  463. m.Get("\\.git$", repo.Home)
  464. }, ignSignIn, middleware.RepoAssignment(true), middleware.RepoRef())
  465. m.Group("/:reponame", func() {
  466. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  467. m.Head("/tasks/trigger", repo.TriggerTask)
  468. })
  469. })
  470. // ***** END: Repository *****
  471. // robots.txt
  472. m.Get("/robots.txt", func(ctx *middleware.Context) {
  473. if setting.HasRobotsTxt {
  474. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  475. } else {
  476. ctx.Error(404)
  477. }
  478. })
  479. // Not found handler.
  480. m.NotFound(routers.NotFound)
  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. }