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.

572 lines
19 KiB

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