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
19 KiB

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