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.

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