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.

590 lines
20 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
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
8 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. "io/ioutil"
  9. "net/http"
  10. "net/http/fcgi"
  11. "os"
  12. "path"
  13. "strings"
  14. "github.com/codegangsta/cli"
  15. "github.com/go-macaron/binding"
  16. "github.com/go-macaron/cache"
  17. "github.com/go-macaron/captcha"
  18. "github.com/go-macaron/csrf"
  19. "github.com/go-macaron/gzip"
  20. "github.com/go-macaron/i18n"
  21. "github.com/go-macaron/session"
  22. "github.com/go-macaron/toolbox"
  23. "github.com/go-xorm/xorm"
  24. "github.com/mcuadros/go-version"
  25. "gopkg.in/ini.v1"
  26. "gopkg.in/macaron.v1"
  27. "github.com/gogits/git-module"
  28. "github.com/gogits/go-gogs-client"
  29. "github.com/gogits/gogs/models"
  30. "github.com/gogits/gogs/modules/auth"
  31. "github.com/gogits/gogs/modules/bindata"
  32. "github.com/gogits/gogs/modules/context"
  33. "github.com/gogits/gogs/modules/log"
  34. "github.com/gogits/gogs/modules/setting"
  35. "github.com/gogits/gogs/modules/template"
  36. "github.com/gogits/gogs/routers"
  37. "github.com/gogits/gogs/routers/admin"
  38. apiv1 "github.com/gogits/gogs/routers/api/v1"
  39. "github.com/gogits/gogs/routers/dev"
  40. "github.com/gogits/gogs/routers/org"
  41. "github.com/gogits/gogs/routers/repo"
  42. "github.com/gogits/gogs/routers/user"
  43. )
  44. var CmdWeb = cli.Command{
  45. Name: "web",
  46. Usage: "Start Gogs web server",
  47. Description: `Gogs web server is the only thing you need to run,
  48. and it takes care of all the other things for you`,
  49. Action: runWeb,
  50. Flags: []cli.Flag{
  51. stringFlag("port, p", "3000", "Temporary port number to prevent conflict"),
  52. stringFlag("config, c", "custom/conf/app.ini", "Custom configuration file path"),
  53. },
  54. }
  55. type VerChecker struct {
  56. ImportPath string
  57. Version func() string
  58. Expected string
  59. }
  60. // checkVersion checks if binary matches the version of templates files.
  61. func checkVersion() {
  62. // Templates.
  63. data, err := ioutil.ReadFile(setting.StaticRootPath + "/templates/.VERSION")
  64. if err != nil {
  65. log.Fatal(4, "Fail to read 'templates/.VERSION': %v", err)
  66. }
  67. if string(data) != setting.AppVer {
  68. log.Fatal(4, "Binary and template file version does not match, did you forget to recompile?")
  69. }
  70. // Check dependency version.
  71. checkers := []VerChecker{
  72. {"github.com/go-xorm/xorm", func() string { return xorm.Version }, "0.5.2.0304"},
  73. {"github.com/go-macaron/binding", binding.Version, "0.2.1"},
  74. {"github.com/go-macaron/cache", cache.Version, "0.1.2"},
  75. {"github.com/go-macaron/csrf", csrf.Version, "0.1.0"},
  76. {"github.com/go-macaron/i18n", i18n.Version, "0.3.0"},
  77. {"github.com/go-macaron/session", session.Version, "0.1.6"},
  78. {"github.com/go-macaron/toolbox", toolbox.Version, "0.1.0"},
  79. {"gopkg.in/ini.v1", ini.Version, "1.8.4"},
  80. {"gopkg.in/macaron.v1", macaron.Version, "1.1.2"},
  81. {"github.com/gogits/git-module", git.Version, "0.3.0"},
  82. {"github.com/gogits/go-gogs-client", gogs.Version, "0.7.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(gzip.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. AppendDirectories: []string{path.Join(setting.CustomPath, "templates")},
  119. Funcs: template.NewFuncMap(),
  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. Cookie: setting.CSRFCookieName,
  151. SetCookie: true,
  152. Header: "X-Csrf-Token",
  153. CookiePath: setting.AppSubUrl,
  154. }))
  155. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  156. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  157. &toolbox.HealthCheckFuncDesc{
  158. Desc: "Database connection",
  159. Func: models.Ping,
  160. },
  161. },
  162. }))
  163. m.Use(context.Contexter())
  164. return m
  165. }
  166. func runWeb(ctx *cli.Context) error {
  167. if ctx.IsSet("config") {
  168. setting.CustomConf = ctx.String("config")
  169. }
  170. routers.GlobalInit()
  171. checkVersion()
  172. m := newMacaron()
  173. reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
  174. ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
  175. ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
  176. reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
  177. bindIgnErr := binding.BindIgnErr
  178. // FIXME: not all routes need go through same middlewares.
  179. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  180. // Routers.
  181. m.Get("/", ignSignIn, routers.Home)
  182. m.Group("/explore", func() {
  183. m.Get("", func(ctx *context.Context) {
  184. ctx.Redirect(setting.AppSubUrl + "/explore/repos")
  185. })
  186. m.Get("/repos", routers.ExploreRepos)
  187. m.Get("/users", routers.ExploreUsers)
  188. }, ignSignIn)
  189. m.Combo("/install", routers.InstallInit).Get(routers.Install).
  190. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  191. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  192. // ***** START: User *****
  193. m.Group("/user", func() {
  194. m.Get("/login", user.SignIn)
  195. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  196. m.Get("/sign_up", user.SignUp)
  197. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  198. m.Get("/reset_password", user.ResetPasswd)
  199. m.Post("/reset_password", user.ResetPasswdPost)
  200. }, reqSignOut)
  201. m.Group("/user/settings", func() {
  202. m.Get("", user.Settings)
  203. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  204. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), user.SettingsAvatar)
  205. m.Post("/avatar/delete", user.SettingsDeleteAvatar)
  206. m.Combo("/email").Get(user.SettingsEmails).
  207. Post(bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  208. m.Post("/email/delete", user.DeleteEmail)
  209. m.Get("/password", user.SettingsPassword)
  210. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  211. m.Combo("/ssh").Get(user.SettingsSSHKeys).
  212. Post(bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  213. m.Post("/ssh/delete", user.DeleteSSHKey)
  214. m.Combo("/applications").Get(user.SettingsApplications).
  215. Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  216. m.Post("/applications/delete", user.SettingsDeleteApplication)
  217. m.Route("/delete", "GET,POST", user.SettingsDelete)
  218. }, reqSignIn, func(ctx *context.Context) {
  219. ctx.Data["PageIsUserSettings"] = true
  220. })
  221. m.Group("/user", func() {
  222. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  223. m.Any("/activate", user.Activate)
  224. m.Any("/activate_email", user.ActivateEmail)
  225. m.Get("/email2user", user.Email2User)
  226. m.Get("/forget_password", user.ForgotPasswd)
  227. m.Post("/forget_password", user.ForgotPasswdPost)
  228. m.Get("/logout", user.SignOut)
  229. })
  230. // ***** END: User *****
  231. adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  232. // ***** START: Admin *****
  233. m.Group("/admin", func() {
  234. m.Get("", adminReq, admin.Dashboard)
  235. m.Get("/config", admin.Config)
  236. m.Post("/config/test_mail", admin.SendTestMail)
  237. m.Get("/monitor", admin.Monitor)
  238. m.Group("/users", func() {
  239. m.Get("", admin.Users)
  240. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCrateUserForm{}), admin.NewUserPost)
  241. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  242. m.Post("/:userid/delete", admin.DeleteUser)
  243. })
  244. m.Group("/orgs", func() {
  245. m.Get("", admin.Organizations)
  246. })
  247. m.Group("/repos", func() {
  248. m.Get("", admin.Repos)
  249. m.Post("/delete", admin.DeleteRepo)
  250. })
  251. m.Group("/auths", func() {
  252. m.Get("", admin.Authentications)
  253. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  254. m.Combo("/:authid").Get(admin.EditAuthSource).
  255. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  256. m.Post("/:authid/delete", admin.DeleteAuthSource)
  257. })
  258. m.Group("/notices", func() {
  259. m.Get("", admin.Notices)
  260. m.Post("/delete", admin.DeleteNotices)
  261. m.Get("/empty", admin.EmptyNotices)
  262. })
  263. }, adminReq)
  264. // ***** END: Admin *****
  265. m.Group("", func() {
  266. m.Group("/:username", func() {
  267. m.Get("", user.Profile)
  268. m.Get("/followers", user.Followers)
  269. m.Get("/following", user.Following)
  270. m.Get("/stars", user.Stars)
  271. })
  272. m.Get("/attachments/:uuid", func(ctx *context.Context) {
  273. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  274. if err != nil {
  275. if models.IsErrAttachmentNotExist(err) {
  276. ctx.Error(404)
  277. } else {
  278. ctx.Handle(500, "GetAttachmentByUUID", err)
  279. }
  280. return
  281. }
  282. fr, err := os.Open(attach.LocalPath())
  283. if err != nil {
  284. ctx.Handle(500, "Open", err)
  285. return
  286. }
  287. defer fr.Close()
  288. ctx.Header().Set("Cache-Control", "public,max-age=86400")
  289. // Fix #312. Attachments with , in their name are not handled correctly by Google Chrome.
  290. // We must put the name in " manually.
  291. if err = repo.ServeData(ctx, "\""+attach.Name+"\"", fr); err != nil {
  292. ctx.Handle(500, "ServeData", err)
  293. return
  294. }
  295. })
  296. m.Post("/issues/attachments", repo.UploadIssueAttachment)
  297. }, ignSignIn)
  298. m.Group("/:username", func() {
  299. m.Get("/action/:action", user.Action)
  300. }, reqSignIn)
  301. if macaron.Env == macaron.DEV {
  302. m.Get("/template/*", dev.TemplatePreview)
  303. }
  304. reqRepoAdmin := context.RequireRepoAdmin()
  305. reqRepoWriter := context.RequireRepoWriter()
  306. // ***** START: Organization *****
  307. m.Group("/org", func() {
  308. m.Get("/create", org.Create)
  309. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  310. m.Group("/:org", func() {
  311. m.Get("/dashboard", user.Dashboard)
  312. m.Get("/^:type(issues|pulls)$", user.Issues)
  313. m.Get("/members", org.Members)
  314. m.Get("/members/action/:action", org.MembersAction)
  315. m.Get("/teams", org.Teams)
  316. }, context.OrgAssignment(true))
  317. m.Group("/:org", func() {
  318. m.Get("/teams/:team", org.TeamMembers)
  319. m.Get("/teams/:team/repositories", org.TeamRepositories)
  320. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  321. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  322. }, context.OrgAssignment(true, false, true))
  323. m.Group("/:org", func() {
  324. m.Get("/teams/new", org.NewTeam)
  325. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  326. m.Get("/teams/:team/edit", org.EditTeam)
  327. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  328. m.Post("/teams/:team/delete", org.DeleteTeam)
  329. m.Group("/settings", func() {
  330. m.Combo("").Get(org.Settings).
  331. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  332. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), org.SettingsAvatar)
  333. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  334. m.Group("/hooks", func() {
  335. m.Get("", org.Webhooks)
  336. m.Post("/delete", org.DeleteWebhook)
  337. m.Get("/:type/new", repo.WebhooksNew)
  338. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  339. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  340. m.Get("/:id", repo.WebHooksEdit)
  341. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  342. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  343. })
  344. m.Route("/delete", "GET,POST", org.SettingsDelete)
  345. })
  346. m.Route("/invitations/new", "GET,POST", org.Invitation)
  347. }, context.OrgAssignment(true, true))
  348. }, reqSignIn)
  349. // ***** END: Organization *****
  350. // ***** START: Repository *****
  351. m.Group("/repo", func() {
  352. m.Get("/create", repo.Create)
  353. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  354. m.Get("/migrate", repo.Migrate)
  355. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  356. m.Combo("/fork/:repoid").Get(repo.Fork).
  357. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  358. }, reqSignIn)
  359. m.Group("/:username/:reponame", func() {
  360. m.Group("/settings", func() {
  361. m.Combo("").Get(repo.Settings).
  362. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  363. m.Group("/collaboration", func() {
  364. m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
  365. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  366. m.Post("/delete", repo.DeleteCollaboration)
  367. })
  368. m.Group("/hooks", func() {
  369. m.Get("", repo.Webhooks)
  370. m.Post("/delete", repo.DeleteWebhook)
  371. m.Get("/:type/new", repo.WebhooksNew)
  372. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  373. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  374. m.Get("/:id", repo.WebHooksEdit)
  375. m.Post("/:id/test", repo.TestWebhook)
  376. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  377. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  378. m.Group("/git", func() {
  379. m.Get("", repo.GitHooks)
  380. m.Combo("/:name").Get(repo.GitHooksEdit).
  381. Post(repo.GitHooksEditPost)
  382. }, context.GitHookService())
  383. })
  384. m.Group("/keys", func() {
  385. m.Combo("").Get(repo.DeployKeys).
  386. Post(bindIgnErr(auth.AddSSHKeyForm{}), repo.DeployKeysPost)
  387. m.Post("/delete", repo.DeleteDeployKey)
  388. })
  389. }, func(ctx *context.Context) {
  390. ctx.Data["PageIsSettings"] = true
  391. })
  392. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
  393. m.Get("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  394. m.Group("/:username/:reponame", func() {
  395. m.Group("/issues", func() {
  396. m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
  397. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  398. m.Combo("/:index/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  399. m.Group("/:index", func() {
  400. m.Post("/label", repo.UpdateIssueLabel)
  401. m.Post("/milestone", repo.UpdateIssueMilestone)
  402. m.Post("/assignee", repo.UpdateIssueAssignee)
  403. }, reqRepoWriter)
  404. m.Group("/:index", func() {
  405. m.Post("/title", repo.UpdateIssueTitle)
  406. m.Post("/content", repo.UpdateIssueContent)
  407. })
  408. })
  409. m.Post("/comments/:id", repo.UpdateCommentContent)
  410. m.Group("/labels", func() {
  411. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  412. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  413. m.Post("/delete", repo.DeleteLabel)
  414. }, reqRepoWriter, context.RepoRef())
  415. m.Group("/milestones", func() {
  416. m.Combo("/new").Get(repo.NewMilestone).
  417. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  418. m.Get("/:id/edit", repo.EditMilestone)
  419. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  420. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  421. m.Post("/delete", repo.DeleteMilestone)
  422. }, reqRepoWriter, context.RepoRef())
  423. m.Group("/releases", func() {
  424. m.Get("/new", repo.NewRelease)
  425. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  426. m.Get("/edit/:tagname", repo.EditRelease)
  427. m.Post("/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  428. m.Post("/delete", repo.DeleteRelease)
  429. }, reqRepoWriter, context.RepoRef())
  430. m.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest).
  431. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  432. }, reqSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  433. m.Group("/:username/:reponame", func() {
  434. m.Group("", func() {
  435. m.Get("/releases", repo.Releases)
  436. m.Get("/^:type(issues|pulls)$", repo.RetrieveLabels, repo.Issues)
  437. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  438. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  439. m.Get("/milestones", repo.Milestones)
  440. }, context.RepoRef())
  441. // m.Get("/branches", repo.Branches)
  442. m.Group("/wiki", func() {
  443. m.Get("/?:page", repo.Wiki)
  444. m.Get("/_pages", repo.WikiPages)
  445. m.Group("", func() {
  446. m.Combo("/_new").Get(repo.NewWiki).
  447. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  448. m.Combo("/:page/_edit").Get(repo.EditWiki).
  449. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  450. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  451. }, reqSignIn, reqRepoWriter)
  452. }, repo.MustEnableWiki, context.RepoRef())
  453. m.Get("/archive/*", repo.Download)
  454. m.Group("/pulls/:index", func() {
  455. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  456. m.Get("/files", context.RepoRef(), repo.ViewPullFiles)
  457. m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  458. }, repo.MustAllowPulls)
  459. m.Group("", func() {
  460. m.Get("/src/*", repo.Home)
  461. m.Get("/raw/*", repo.SingleDownload)
  462. m.Get("/commits/*", repo.RefCommits)
  463. m.Get("/commit/:sha([a-z0-9]{40})$", repo.Diff)
  464. m.Get("/forks", repo.Forks)
  465. }, context.RepoRef())
  466. m.Get("/commit/:sha([a-z0-9]{40})\\.:ext(patch|diff)", repo.RawDiff)
  467. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.CompareDiff)
  468. }, ignSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  469. m.Group("/:username/:reponame", func() {
  470. m.Get("/stars", repo.Stars)
  471. m.Get("/watchers", repo.Watchers)
  472. }, ignSignIn, context.RepoAssignment(), context.RepoRef())
  473. m.Group("/:username", func() {
  474. m.Group("/:reponame", func() {
  475. m.Get("", repo.Home)
  476. m.Get("\\.git$", repo.Home)
  477. }, ignSignIn, context.RepoAssignment(true), context.RepoRef())
  478. m.Group("/:reponame", func() {
  479. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  480. m.Head("/tasks/trigger", repo.TriggerTask)
  481. })
  482. })
  483. // ***** END: Repository *****
  484. m.Group("/api", func() {
  485. apiv1.RegisterRoutes(m)
  486. }, ignSignIn)
  487. // robots.txt
  488. m.Get("/robots.txt", func(ctx *context.Context) {
  489. if setting.HasRobotsTxt {
  490. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  491. } else {
  492. ctx.Error(404)
  493. }
  494. })
  495. // Not found handler.
  496. m.NotFound(routers.NotFound)
  497. // Flag for port number in case first time run conflict.
  498. if ctx.IsSet("port") {
  499. setting.AppUrl = strings.Replace(setting.AppUrl, setting.HttpPort, ctx.String("port"), 1)
  500. setting.HttpPort = ctx.String("port")
  501. }
  502. var err error
  503. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  504. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  505. switch setting.Protocol {
  506. case setting.HTTP:
  507. err = http.ListenAndServe(listenAddr, m)
  508. case setting.HTTPS:
  509. server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS10}, Handler: m}
  510. err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  511. case setting.FCGI:
  512. err = fcgi.Serve(nil, m)
  513. default:
  514. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  515. }
  516. if err != nil {
  517. log.Fatal(4, "Fail to start server: %v", err)
  518. }
  519. return nil
  520. }