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.

599 lines
20 KiB

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
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
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. 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/bindata"
  34. "github.com/gogits/gogs/modules/log"
  35. "github.com/gogits/gogs/modules/middleware"
  36. "github.com/gogits/gogs/modules/setting"
  37. "github.com/gogits/gogs/modules/template"
  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. stringFlag("port, p", "3000", "Temporary port number to prevent conflict"),
  54. 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. {"github.com/go-macaron/toolbox", toolbox.Version, "0.1.0"},
  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(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. Funcs: []gotmpl.FuncMap{template.Funcs},
  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. m.Use(middleware.Contexter())
  161. return m
  162. }
  163. func runWeb(ctx *cli.Context) {
  164. if ctx.IsSet("config") {
  165. setting.CustomConf = ctx.String("config")
  166. }
  167. routers.GlobalInit()
  168. checkVersion()
  169. m := newMacaron()
  170. reqSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true})
  171. ignSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: setting.Service.RequireSignInView})
  172. ignSignInAndCsrf := middleware.Toggle(&middleware.ToggleOptions{DisableCsrf: true})
  173. reqSignOut := middleware.Toggle(&middleware.ToggleOptions{SignOutRequire: true})
  174. bind := binding.Bind
  175. bindIgnErr := binding.BindIgnErr
  176. // Routers.
  177. m.Get("/", ignSignIn, routers.Home)
  178. m.Get("/explore", ignSignIn, routers.Explore)
  179. m.Combo("/install", routers.InstallInit).Get(routers.Install).
  180. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  181. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  182. // ***** START: API *****
  183. // FIXME: custom form error response.
  184. m.Group("/api", func() {
  185. m.Group("/v1", func() {
  186. // Miscellaneous.
  187. m.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown)
  188. m.Post("/markdown/raw", v1.MarkdownRaw)
  189. // Users.
  190. m.Group("/users", func() {
  191. m.Get("/search", v1.SearchUsers)
  192. m.Group("/:username", func() {
  193. m.Get("", v1.GetUserInfo)
  194. m.Group("/tokens", func() {
  195. m.Combo("").Get(v1.ListAccessTokens).
  196. Post(bind(v1.CreateAccessTokenForm{}), v1.CreateAccessToken)
  197. }, middleware.ApiReqBasicAuth())
  198. })
  199. })
  200. // Repositories.
  201. m.Combo("/user/repos", middleware.ApiReqToken()).Get(v1.ListMyRepos).
  202. Post(bind(api.CreateRepoOption{}), v1.CreateRepo)
  203. m.Post("/org/:org/repos", middleware.ApiReqToken(), bind(api.CreateRepoOption{}), v1.CreateOrgRepo)
  204. m.Group("/repos", func() {
  205. m.Get("/search", v1.SearchRepos)
  206. })
  207. m.Group("/repos", func() {
  208. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), v1.MigrateRepo)
  209. m.Combo("/:username/:reponame").Get(v1.GetRepo).
  210. Delete(v1.DeleteRepo)
  211. m.Group("/:username/:reponame", func() {
  212. m.Combo("/hooks").Get(v1.ListRepoHooks).
  213. Post(bind(api.CreateHookOption{}), v1.CreateRepoHook)
  214. m.Patch("/hooks/:id:int", bind(api.EditHookOption{}), v1.EditRepoHook)
  215. m.Get("/raw/*", middleware.RepoRef(), v1.GetRepoRawFile)
  216. m.Get("/archive/*", v1.GetRepoArchive)
  217. }, middleware.ApiRepoAssignment())
  218. }, middleware.ApiReqToken())
  219. m.Any("/*", func(ctx *middleware.Context) {
  220. ctx.Error(404)
  221. })
  222. })
  223. }, ignSignIn)
  224. // ***** END: API *****
  225. // ***** START: User *****
  226. m.Group("/user", func() {
  227. m.Get("/login", user.SignIn)
  228. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  229. m.Get("/sign_up", user.SignUp)
  230. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  231. m.Get("/reset_password", user.ResetPasswd)
  232. m.Post("/reset_password", user.ResetPasswdPost)
  233. }, reqSignOut)
  234. m.Group("/user/settings", func() {
  235. m.Get("", user.Settings)
  236. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  237. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), user.SettingsAvatar)
  238. m.Combo("/email").Get(user.SettingsEmails).
  239. Post(bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  240. m.Post("/email/delete", user.DeleteEmail)
  241. m.Get("/password", user.SettingsPassword)
  242. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  243. m.Combo("/ssh").Get(user.SettingsSSHKeys).
  244. Post(bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  245. m.Post("/ssh/delete", user.DeleteSSHKey)
  246. m.Combo("/applications").Get(user.SettingsApplications).
  247. Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  248. m.Post("/applications/delete", user.SettingsDeleteApplication)
  249. m.Route("/delete", "GET,POST", user.SettingsDelete)
  250. }, reqSignIn, func(ctx *middleware.Context) {
  251. ctx.Data["PageIsUserSettings"] = true
  252. })
  253. m.Group("/user", func() {
  254. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  255. m.Any("/activate", user.Activate)
  256. m.Any("/activate_email", user.ActivateEmail)
  257. m.Get("/email2user", user.Email2User)
  258. m.Get("/forget_password", user.ForgotPasswd)
  259. m.Post("/forget_password", user.ForgotPasswdPost)
  260. m.Get("/logout", user.SignOut)
  261. })
  262. // ***** END: User *****
  263. // Gravatar service.
  264. avt := avatar.CacheServer("public/img/avatar/", "public/img/avatar_default.jpg")
  265. os.MkdirAll("public/img/avatar/", os.ModePerm)
  266. m.Get("/avatar/:hash", avt.ServeHTTP)
  267. adminReq := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true, AdminRequire: true})
  268. // ***** START: Admin *****
  269. m.Group("/admin", func() {
  270. m.Get("", adminReq, admin.Dashboard)
  271. m.Get("/config", admin.Config)
  272. m.Get("/monitor", admin.Monitor)
  273. m.Group("/users", func() {
  274. m.Get("", admin.Users)
  275. m.Get("/new", admin.NewUser)
  276. m.Post("/new", bindIgnErr(auth.AdminCrateUserForm{}), admin.NewUserPost)
  277. m.Get("/:userid", admin.EditUser)
  278. m.Post("/:userid", bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  279. m.Post("/:userid/delete", admin.DeleteUser)
  280. })
  281. m.Group("/orgs", func() {
  282. m.Get("", admin.Organizations)
  283. })
  284. m.Group("/repos", func() {
  285. m.Get("", admin.Repositories)
  286. })
  287. m.Group("/auths", func() {
  288. m.Get("", admin.Authentications)
  289. m.Get("/new", admin.NewAuthSource)
  290. m.Post("/new", bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  291. m.Combo("/:authid").Get(admin.EditAuthSource).
  292. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  293. m.Post("/:authid/delete", admin.DeleteAuthSource)
  294. })
  295. m.Group("/notices", func() {
  296. m.Get("", admin.Notices)
  297. m.Get("/:id:int/delete", admin.DeleteNotice)
  298. })
  299. }, adminReq)
  300. // ***** END: Admin *****
  301. m.Group("", func() {
  302. m.Get("/:username", user.Profile)
  303. m.Get("/attachments/:uuid", func(ctx *middleware.Context) {
  304. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  305. if err != nil {
  306. if models.IsErrAttachmentNotExist(err) {
  307. ctx.Error(404)
  308. } else {
  309. ctx.Handle(500, "GetAttachmentByUUID", err)
  310. }
  311. return
  312. }
  313. fr, err := os.Open(attach.LocalPath())
  314. if err != nil {
  315. ctx.Handle(500, "Open", err)
  316. return
  317. }
  318. defer fr.Close()
  319. ctx.Header().Set("Cache-Control", "public,max-age=86400")
  320. // Fix #312. Attachments with , in their name are not handled correctly by Google Chrome.
  321. // We must put the name in " manually.
  322. if err = repo.ServeData(ctx, "\""+attach.Name+"\"", fr); err != nil {
  323. ctx.Handle(500, "ServeData", err)
  324. return
  325. }
  326. })
  327. m.Post("/issues/attachments", repo.UploadIssueAttachment)
  328. }, ignSignIn)
  329. if macaron.Env == macaron.DEV {
  330. m.Get("/template/*", dev.TemplatePreview)
  331. }
  332. reqRepoAdmin := middleware.RequireRepoAdmin()
  333. // ***** START: Organization *****
  334. m.Group("/org", func() {
  335. m.Get("/create", org.Create)
  336. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  337. m.Group("/:org", func() {
  338. m.Get("/dashboard", user.Dashboard)
  339. m.Get("/^:type(issues|pulls)$", user.Issues)
  340. m.Get("/members", org.Members)
  341. m.Get("/members/action/:action", org.MembersAction)
  342. m.Get("/teams", org.Teams)
  343. m.Get("/teams/:team", org.TeamMembers)
  344. m.Get("/teams/:team/repositories", org.TeamRepositories)
  345. m.Get("/teams/:team/action/:action", org.TeamsAction)
  346. m.Get("/teams/:team/action/repo/:action", org.TeamsRepoAction)
  347. }, middleware.OrgAssignment(true, true))
  348. m.Group("/:org", func() {
  349. m.Get("/teams/new", org.NewTeam)
  350. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  351. m.Get("/teams/:team/edit", org.EditTeam)
  352. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  353. m.Post("/teams/:team/delete", org.DeleteTeam)
  354. m.Group("/settings", func() {
  355. m.Combo("").Get(org.Settings).
  356. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  357. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), org.SettingsAvatar)
  358. m.Group("/hooks", func() {
  359. m.Get("", org.Webhooks)
  360. m.Post("/delete", org.DeleteWebhook)
  361. m.Get("/:type/new", repo.WebhooksNew)
  362. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  363. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  364. m.Get("/:id", repo.WebHooksEdit)
  365. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  366. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  367. })
  368. m.Route("/delete", "GET,POST", org.SettingsDelete)
  369. })
  370. m.Route("/invitations/new", "GET,POST", org.Invitation)
  371. }, middleware.OrgAssignment(true, true, true))
  372. }, reqSignIn)
  373. m.Group("/org", func() {
  374. m.Get("/:org", org.Home)
  375. }, ignSignIn, middleware.OrgAssignment(true))
  376. // ***** END: Organization *****
  377. // ***** START: Repository *****
  378. m.Group("/repo", func() {
  379. m.Get("/create", repo.Create)
  380. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  381. m.Get("/migrate", repo.Migrate)
  382. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  383. m.Combo("/fork/:repoid").Get(repo.Fork).
  384. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  385. }, reqSignIn)
  386. m.Group("/:username/:reponame", func() {
  387. m.Group("/settings", func() {
  388. m.Combo("").Get(repo.Settings).
  389. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  390. m.Route("/collaboration", "GET,POST", repo.Collaboration)
  391. m.Group("/hooks", func() {
  392. m.Get("", repo.Webhooks)
  393. m.Post("/delete", repo.DeleteWebhook)
  394. m.Get("/:type/new", repo.WebhooksNew)
  395. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  396. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  397. m.Get("/:id", repo.WebHooksEdit)
  398. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  399. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  400. m.Group("/git", func() {
  401. m.Get("", repo.GitHooks)
  402. m.Combo("/:name").Get(repo.GitHooksEdit).
  403. Post(repo.GitHooksEditPost)
  404. }, middleware.GitHookService())
  405. })
  406. m.Group("/keys", func() {
  407. m.Combo("").Get(repo.DeployKeys).
  408. Post(bindIgnErr(auth.AddSSHKeyForm{}), repo.DeployKeysPost)
  409. m.Post("/delete", repo.DeleteDeployKey)
  410. })
  411. }, func(ctx *middleware.Context) {
  412. ctx.Data["PageIsSettings"] = true
  413. })
  414. }, reqSignIn, middleware.RepoAssignment(true), reqRepoAdmin, middleware.RepoRef())
  415. m.Group("/:username/:reponame", func() {
  416. m.Get("/action/:action", repo.Action)
  417. m.Group("/issues", func() {
  418. m.Combo("/new").Get(repo.NewIssue).
  419. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  420. m.Combo("/:index/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  421. m.Group("/:index", func() {
  422. m.Post("/label", repo.UpdateIssueLabel)
  423. m.Post("/milestone", repo.UpdateIssueMilestone)
  424. m.Post("/assignee", repo.UpdateIssueAssignee)
  425. }, reqRepoAdmin)
  426. m.Group("/:index", func() {
  427. m.Post("/title", repo.UpdateIssueTitle)
  428. m.Post("/content", repo.UpdateIssueContent)
  429. })
  430. })
  431. m.Post("/comments/:id", repo.UpdateCommentContent)
  432. m.Group("/labels", func() {
  433. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  434. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  435. m.Post("/delete", repo.DeleteLabel)
  436. }, reqRepoAdmin)
  437. m.Group("/milestones", func() {
  438. m.Get("/new", repo.NewMilestone)
  439. m.Post("/new", bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  440. m.Get("/:id/edit", repo.EditMilestone)
  441. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  442. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  443. m.Post("/delete", repo.DeleteMilestone)
  444. }, reqRepoAdmin)
  445. m.Group("/releases", func() {
  446. m.Get("/new", repo.NewRelease)
  447. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  448. m.Get("/edit/:tagname", repo.EditRelease)
  449. m.Post("/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  450. }, reqRepoAdmin, middleware.RepoRef())
  451. m.Combo("/compare/*").Get(repo.CompareAndPullRequest).
  452. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  453. }, reqSignIn, middleware.RepoAssignment(true))
  454. m.Group("/:username/:reponame", func() {
  455. m.Group("", func() {
  456. m.Get("/releases", repo.Releases)
  457. m.Get("/^:type(issues|pulls)$", repo.RetrieveLabels, repo.Issues)
  458. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  459. m.Get("/milestones", repo.Milestones)
  460. }, middleware.RepoRef(),
  461. func(ctx *middleware.Context) {
  462. ctx.Data["PageIsList"] = true
  463. })
  464. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  465. m.Get("/branches", repo.Branches)
  466. m.Get("/archive/*", repo.Download)
  467. m.Group("/pulls/:index", func() {
  468. m.Get("/commits", repo.ViewPullCommits)
  469. m.Get("/files", repo.ViewPullFiles)
  470. m.Post("/merge", reqRepoAdmin, repo.MergePullRequest)
  471. })
  472. m.Group("", func() {
  473. m.Get("/src/*", repo.Home)
  474. m.Get("/raw/*", repo.SingleDownload)
  475. m.Get("/commits/*", repo.RefCommits)
  476. m.Get("/commit/*", repo.Diff)
  477. m.Get("/stars", repo.Stars)
  478. m.Get("/watchers", repo.Watchers)
  479. m.Get("/forks", repo.Forks)
  480. }, middleware.RepoRef())
  481. m.Get("/compare/:before([a-z0-9]{40})...:after([a-z0-9]{40})", repo.CompareDiff)
  482. }, ignSignIn, middleware.RepoAssignment(true))
  483. m.Group("/:username", func() {
  484. m.Group("/:reponame", func() {
  485. m.Get("", repo.Home)
  486. m.Get("\\.git$", repo.Home)
  487. }, ignSignIn, middleware.RepoAssignment(true, true), middleware.RepoRef())
  488. m.Group("/:reponame", func() {
  489. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  490. m.Head("/tasks/trigger", repo.TriggerTask)
  491. })
  492. })
  493. // ***** END: Repository *****
  494. // robots.txt
  495. m.Get("/robots.txt", func(ctx *middleware.Context) {
  496. if setting.HasRobotsTxt {
  497. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  498. } else {
  499. ctx.Error(404)
  500. }
  501. })
  502. // Not found handler.
  503. m.NotFound(routers.NotFound)
  504. // Flag for port number in case first time run conflict.
  505. if ctx.IsSet("port") {
  506. setting.AppUrl = strings.Replace(setting.AppUrl, setting.HttpPort, ctx.String("port"), 1)
  507. setting.HttpPort = ctx.String("port")
  508. }
  509. var err error
  510. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  511. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  512. switch setting.Protocol {
  513. case setting.HTTP:
  514. err = http.ListenAndServe(listenAddr, m)
  515. case setting.HTTPS:
  516. server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS10}, Handler: m}
  517. err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  518. case setting.FCGI:
  519. err = fcgi.Serve(nil, m)
  520. default:
  521. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  522. }
  523. if err != nil {
  524. log.Fatal(4, "Fail to start server: %v", err)
  525. }
  526. }