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.

595 lines
20 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
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.Combo("/email").Get(user.SettingsEmails).
  243. Post(bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  244. m.Post("/email/delete", user.DeleteEmail)
  245. m.Get("/password", user.SettingsPassword)
  246. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  247. m.Combo("/ssh").Get(user.SettingsSSHKeys).
  248. Post(bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  249. m.Post("/ssh/delete", user.DeleteSSHKey)
  250. m.Get("/social", user.SettingsSocial)
  251. m.Combo("/applications").Get(user.SettingsApplications).
  252. Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  253. m.Post("/applications/delete", user.SettingsDeleteApplication)
  254. m.Route("/delete", "GET,POST", user.SettingsDelete)
  255. }, reqSignIn, func(ctx *middleware.Context) {
  256. ctx.Data["PageIsUserSettings"] = true
  257. ctx.Data["HasOAuthService"] = setting.OauthService != nil
  258. })
  259. m.Group("/user", func() {
  260. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  261. m.Any("/activate", user.Activate)
  262. m.Any("/activate_email", user.ActivateEmail)
  263. m.Get("/email2user", user.Email2User)
  264. m.Get("/forget_password", user.ForgotPasswd)
  265. m.Post("/forget_password", user.ForgotPasswdPost)
  266. m.Get("/logout", user.SignOut)
  267. })
  268. // ***** END: User *****
  269. // Gravatar service.
  270. avt := avatar.CacheServer("public/img/avatar/", "public/img/avatar_default.jpg")
  271. os.MkdirAll("public/img/avatar/", os.ModePerm)
  272. m.Get("/avatar/:hash", avt.ServeHTTP)
  273. adminReq := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true, AdminRequire: true})
  274. // ***** START: Admin *****
  275. m.Group("/admin", func() {
  276. m.Get("", adminReq, admin.Dashboard)
  277. m.Get("/config", admin.Config)
  278. m.Get("/monitor", admin.Monitor)
  279. m.Group("/users", func() {
  280. m.Get("", admin.Users)
  281. m.Get("/new", admin.NewUser)
  282. m.Post("/new", bindIgnErr(auth.AdminCrateUserForm{}), admin.NewUserPost)
  283. m.Get("/:userid", admin.EditUser)
  284. m.Post("/:userid", bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  285. m.Post("/:userid/delete", admin.DeleteUser)
  286. })
  287. m.Group("/orgs", func() {
  288. m.Get("", admin.Organizations)
  289. })
  290. m.Group("/repos", func() {
  291. m.Get("", admin.Repositories)
  292. })
  293. m.Group("/auths", func() {
  294. m.Get("", admin.Authentications)
  295. m.Get("/new", admin.NewAuthSource)
  296. m.Post("/new", bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  297. m.Combo("/:authid").Get(admin.EditAuthSource).
  298. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  299. m.Post("/:authid/delete", admin.DeleteAuthSource)
  300. })
  301. m.Group("/notices", func() {
  302. m.Get("", admin.Notices)
  303. m.Get("/:id:int/delete", admin.DeleteNotice)
  304. })
  305. }, adminReq)
  306. // ***** END: Admin *****
  307. m.Group("", func() {
  308. m.Get("/:username", user.Profile)
  309. m.Get("/attachments/:uuid", func(ctx *middleware.Context) {
  310. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  311. if err != nil {
  312. if models.IsErrAttachmentNotExist(err) {
  313. ctx.Error(404)
  314. } else {
  315. ctx.Handle(500, "GetAttachmentByUUID", err)
  316. }
  317. return
  318. }
  319. fr, err := os.Open(attach.LocalPath())
  320. if err != nil {
  321. ctx.Handle(500, "Open", err)
  322. return
  323. }
  324. defer fr.Close()
  325. ctx.Header().Set("Cache-Control", "public,max-age=86400")
  326. // Fix #312. Attachments with , in their name are not handled correctly by Google Chrome.
  327. // We must put the name in " manually.
  328. if err = repo.ServeData(ctx, "\""+attach.Name+"\"", fr); err != nil {
  329. ctx.Handle(500, "ServeData", err)
  330. return
  331. }
  332. })
  333. m.Post("/issues/attachments", repo.UploadIssueAttachment)
  334. }, ignSignIn)
  335. if macaron.Env == macaron.DEV {
  336. m.Get("/template/*", dev.TemplatePreview)
  337. }
  338. reqRepoAdmin := middleware.RequireRepoAdmin()
  339. // ***** START: Organization *****
  340. m.Group("/org", func() {
  341. m.Get("/create", org.Create)
  342. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  343. m.Group("/:org", func() {
  344. m.Get("/dashboard", user.Dashboard)
  345. m.Get("/:type(issues|pulls)", user.Issues)
  346. m.Get("/members", org.Members)
  347. m.Get("/members/action/:action", org.MembersAction)
  348. m.Get("/teams", org.Teams)
  349. m.Get("/teams/:team", org.TeamMembers)
  350. m.Get("/teams/:team/repositories", org.TeamRepositories)
  351. m.Get("/teams/:team/action/:action", org.TeamsAction)
  352. m.Get("/teams/:team/action/repo/:action", org.TeamsRepoAction)
  353. }, middleware.OrgAssignment(true, true))
  354. m.Group("/:org", func() {
  355. m.Get("/teams/new", org.NewTeam)
  356. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  357. m.Get("/teams/:team/edit", org.EditTeam)
  358. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  359. m.Post("/teams/:team/delete", org.DeleteTeam)
  360. m.Group("/settings", func() {
  361. m.Combo("").Get(org.Settings).
  362. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  363. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), org.SettingsAvatar)
  364. m.Group("/hooks", func() {
  365. m.Get("", org.Webhooks)
  366. m.Post("/delete", org.DeleteWebhook)
  367. m.Get("/:type/new", repo.WebhooksNew)
  368. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  369. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  370. m.Get("/:id", repo.WebHooksEdit)
  371. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  372. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  373. })
  374. m.Route("/delete", "GET,POST", org.SettingsDelete)
  375. })
  376. m.Route("/invitations/new", "GET,POST", org.Invitation)
  377. }, middleware.OrgAssignment(true, true, true))
  378. }, reqSignIn)
  379. m.Group("/org", func() {
  380. m.Get("/:org", org.Home)
  381. }, ignSignIn, middleware.OrgAssignment(true))
  382. // ***** END: Organization *****
  383. // ***** START: Repository *****
  384. m.Group("/repo", func() {
  385. m.Get("/create", repo.Create)
  386. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  387. m.Get("/migrate", repo.Migrate)
  388. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  389. m.Combo("/fork/:repoid").Get(repo.Fork).
  390. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  391. }, reqSignIn)
  392. m.Group("/:username/:reponame", func() {
  393. m.Group("/settings", func() {
  394. m.Combo("").Get(repo.Settings).
  395. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  396. m.Route("/collaboration", "GET,POST", repo.Collaboration)
  397. m.Group("/hooks", func() {
  398. m.Get("", repo.Webhooks)
  399. m.Post("/delete", repo.DeleteWebhook)
  400. m.Get("/:type/new", repo.WebhooksNew)
  401. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  402. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  403. m.Get("/:id", repo.WebHooksEdit)
  404. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  405. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  406. m.Group("/git", func() {
  407. m.Get("", repo.GitHooks)
  408. m.Combo("/:name").Get(repo.GitHooksEdit).
  409. Post(repo.GitHooksEditPost)
  410. }, middleware.GitHookService())
  411. })
  412. m.Group("/keys", func() {
  413. m.Combo("").Get(repo.DeployKeys).
  414. Post(bindIgnErr(auth.AddSSHKeyForm{}), repo.DeployKeysPost)
  415. m.Post("/delete", repo.DeleteDeployKey)
  416. })
  417. })
  418. }, reqSignIn, middleware.RepoAssignment(true), reqRepoAdmin)
  419. m.Group("/:username/:reponame", func() {
  420. m.Get("/action/:action", repo.Action)
  421. m.Group("/issues", func() {
  422. m.Combo("/new").Get(repo.NewIssue).
  423. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  424. m.Combo("/:index/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  425. m.Group("/:index", func() {
  426. m.Post("/label", repo.UpdateIssueLabel)
  427. m.Post("/milestone", repo.UpdateIssueMilestone)
  428. m.Post("/assignee", repo.UpdateIssueAssignee)
  429. }, reqRepoAdmin)
  430. m.Group("/:index", func() {
  431. m.Post("/title", repo.UpdateIssueTitle)
  432. m.Post("/content", repo.UpdateIssueContent)
  433. })
  434. })
  435. m.Post("/comments/:id", repo.UpdateCommentContent)
  436. m.Group("/labels", func() {
  437. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  438. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  439. m.Post("/delete", repo.DeleteLabel)
  440. }, reqRepoAdmin)
  441. m.Group("/milestones", func() {
  442. m.Get("/new", repo.NewMilestone)
  443. m.Post("/new", bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  444. m.Get("/:id/edit", repo.EditMilestone)
  445. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  446. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  447. m.Post("/delete", repo.DeleteMilestone)
  448. }, reqRepoAdmin)
  449. m.Group("/releases", func() {
  450. m.Get("/new", repo.NewRelease)
  451. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  452. m.Get("/edit/:tagname", repo.EditRelease)
  453. m.Post("/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  454. }, reqRepoAdmin, middleware.RepoRef())
  455. m.Combo("/compare/*").Get(repo.CompareAndPullRequest).
  456. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  457. }, reqSignIn, middleware.RepoAssignment(true))
  458. m.Group("/:username/:reponame", func() {
  459. m.Get("/releases", middleware.RepoRef(), repo.Releases)
  460. m.Get("/:type(issues|pulls)", repo.RetrieveLabels, repo.Issues)
  461. m.Get("/:type(issues|pulls)/:index", repo.ViewIssue)
  462. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  463. m.Get("/milestones", repo.Milestones)
  464. m.Get("/branches", repo.Branches)
  465. m.Get("/archive/*", repo.Download)
  466. m.Group("/pulls/:index", func() {
  467. m.Get("/commits", repo.ViewPullCommits)
  468. m.Get("/files", repo.ViewPullFiles)
  469. m.Post("/merge", reqRepoAdmin, repo.MergePullRequest)
  470. })
  471. m.Group("", func() {
  472. m.Get("/src/*", repo.Home)
  473. m.Get("/raw/*", repo.SingleDownload)
  474. m.Get("/commits/*", repo.RefCommits)
  475. m.Get("/commit/*", repo.Diff)
  476. }, middleware.RepoRef())
  477. m.Get("/compare/:before([a-z0-9]{40})...:after([a-z0-9]{40})", repo.CompareDiff)
  478. }, ignSignIn, middleware.RepoAssignment(true))
  479. m.Group("/:username", func() {
  480. m.Group("/:reponame", func() {
  481. m.Get("", repo.Home)
  482. m.Get("\\.git$", repo.Home)
  483. }, ignSignIn, middleware.RepoAssignment(true, true), middleware.RepoRef())
  484. m.Group("/:reponame", func() {
  485. m.Any("/*", ignSignInAndCsrf, repo.Http)
  486. m.Head("/hooks/trigger", repo.TriggerHook)
  487. })
  488. })
  489. // ***** END: Repository *****
  490. // robots.txt
  491. m.Get("/robots.txt", func(ctx *middleware.Context) {
  492. if setting.HasRobotsTxt {
  493. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  494. } else {
  495. ctx.Error(404)
  496. }
  497. })
  498. // Not found handler.
  499. m.NotFound(routers.NotFound)
  500. // Flag for port number in case first time run conflict.
  501. if ctx.IsSet("port") {
  502. setting.AppUrl = strings.Replace(setting.AppUrl, setting.HttpPort, ctx.String("port"), 1)
  503. setting.HttpPort = ctx.String("port")
  504. }
  505. var err error
  506. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  507. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  508. switch setting.Protocol {
  509. case setting.HTTP:
  510. err = http.ListenAndServe(listenAddr, m)
  511. case setting.HTTPS:
  512. server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS10}, Handler: m}
  513. err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  514. case setting.FCGI:
  515. err = fcgi.Serve(nil, m)
  516. default:
  517. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  518. }
  519. if err != nil {
  520. log.Fatal(4, "Fail to start server: %v", err)
  521. }
  522. }