web.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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. "io/ioutil"
  9. "net/http"
  10. "net/http/fcgi"
  11. "os"
  12. "path"
  13. "strings"
  14. "github.com/codegangsta/cli"
  15. "github.com/go-macaron/binding"
  16. "github.com/go-macaron/cache"
  17. "github.com/go-macaron/captcha"
  18. "github.com/go-macaron/csrf"
  19. "github.com/go-macaron/gzip"
  20. "github.com/go-macaron/i18n"
  21. "github.com/go-macaron/session"
  22. "github.com/go-macaron/toolbox"
  23. "github.com/go-xorm/xorm"
  24. "github.com/mcuadros/go-version"
  25. "gopkg.in/ini.v1"
  26. "gopkg.in/macaron.v1"
  27. "github.com/gogits/git-module"
  28. "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/bindata"
  32. "github.com/gogits/gogs/modules/context"
  33. "github.com/gogits/gogs/modules/log"
  34. "github.com/gogits/gogs/modules/setting"
  35. "github.com/gogits/gogs/modules/template"
  36. "github.com/gogits/gogs/routers"
  37. "github.com/gogits/gogs/routers/admin"
  38. apiv1 "github.com/gogits/gogs/routers/api/v1"
  39. "github.com/gogits/gogs/routers/dev"
  40. "github.com/gogits/gogs/routers/org"
  41. "github.com/gogits/gogs/routers/repo"
  42. "github.com/gogits/gogs/routers/user"
  43. )
  44. var CmdWeb = cli.Command{
  45. Name: "web",
  46. Usage: "Start Gogs web server",
  47. Description: `Gogs web server is the only thing you need to run,
  48. and it takes care of all the other things for you`,
  49. Action: runWeb,
  50. Flags: []cli.Flag{
  51. stringFlag("port, p", "3000", "Temporary port number to prevent conflict"),
  52. stringFlag("config, c", "custom/conf/app.ini", "Custom configuration file path"),
  53. },
  54. }
  55. type VerChecker struct {
  56. ImportPath string
  57. Version func() string
  58. Expected string
  59. }
  60. // checkVersion checks if binary matches the version of templates files.
  61. func checkVersion() {
  62. // Templates.
  63. data, err := ioutil.ReadFile(setting.StaticRootPath + "/templates/.VERSION")
  64. if err != nil {
  65. log.Fatal(4, "Fail to read 'templates/.VERSION': %v", err)
  66. }
  67. if string(data) != setting.AppVer {
  68. log.Fatal(4, "Binary and template file version does not match, did you forget to recompile?")
  69. }
  70. // Check dependency version.
  71. checkers := []VerChecker{
  72. {"github.com/go-xorm/xorm", func() string { return xorm.Version }, "0.5.5.0711"},
  73. {"github.com/go-macaron/binding", binding.Version, "0.3.2"},
  74. {"github.com/go-macaron/cache", cache.Version, "0.1.2"},
  75. {"github.com/go-macaron/csrf", csrf.Version, "0.1.0"},
  76. {"github.com/go-macaron/i18n", i18n.Version, "0.3.0"},
  77. {"github.com/go-macaron/session", session.Version, "0.1.6"},
  78. {"github.com/go-macaron/toolbox", toolbox.Version, "0.1.0"},
  79. {"gopkg.in/ini.v1", ini.Version, "1.8.4"},
  80. {"gopkg.in/macaron.v1", macaron.Version, "1.1.2"},
  81. {"github.com/gogits/git-module", git.Version, "0.3.2"},
  82. {"github.com/gogits/go-gogs-client", gogs.Version, "0.7.4"},
  83. }
  84. for _, c := range checkers {
  85. if !version.Compare(c.Version(), c.Expected, ">=") {
  86. log.Fatal(4, `Dependency outdated!
  87. Package '%s' current version (%s) is below requirement (%s),
  88. please use following command to update this package and recompile Gogs:
  89. go get -u %[1]s`, c.ImportPath, c.Version(), c.Expected)
  90. }
  91. }
  92. }
  93. // newMacaron initializes Macaron instance.
  94. func newMacaron() *macaron.Macaron {
  95. m := macaron.New()
  96. if !setting.DisableRouterLog {
  97. m.Use(macaron.Logger())
  98. }
  99. m.Use(macaron.Recovery())
  100. if setting.EnableGzip {
  101. m.Use(gzip.Gziper())
  102. }
  103. if setting.Protocol == setting.FCGI {
  104. m.SetURLPrefix(setting.AppSubUrl)
  105. }
  106. m.Use(macaron.Static(
  107. path.Join(setting.StaticRootPath, "public"),
  108. macaron.StaticOptions{
  109. SkipLogging: setting.DisableRouterLog,
  110. },
  111. ))
  112. m.Use(macaron.Static(
  113. setting.AvatarUploadPath,
  114. macaron.StaticOptions{
  115. Prefix: "avatars",
  116. SkipLogging: setting.DisableRouterLog,
  117. },
  118. ))
  119. m.Use(macaron.Renderer(macaron.RenderOptions{
  120. Directory: path.Join(setting.StaticRootPath, "templates"),
  121. AppendDirectories: []string{path.Join(setting.CustomPath, "templates")},
  122. Funcs: template.NewFuncMap(),
  123. IndentJSON: macaron.Env != macaron.PROD,
  124. }))
  125. localeNames, err := bindata.AssetDir("conf/locale")
  126. if err != nil {
  127. log.Fatal(4, "Fail to list locale files: %v", err)
  128. }
  129. localFiles := make(map[string][]byte)
  130. for _, name := range localeNames {
  131. localFiles[name] = bindata.MustAsset("conf/locale/" + name)
  132. }
  133. m.Use(i18n.I18n(i18n.Options{
  134. SubURL: setting.AppSubUrl,
  135. Files: localFiles,
  136. CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
  137. Langs: setting.Langs,
  138. Names: setting.Names,
  139. DefaultLang: "en-US",
  140. Redirect: true,
  141. }))
  142. m.Use(cache.Cacher(cache.Options{
  143. Adapter: setting.CacheAdapter,
  144. AdapterConfig: setting.CacheConn,
  145. Interval: setting.CacheInternal,
  146. }))
  147. m.Use(captcha.Captchaer(captcha.Options{
  148. SubURL: setting.AppSubUrl,
  149. }))
  150. m.Use(session.Sessioner(setting.SessionConfig))
  151. m.Use(csrf.Csrfer(csrf.Options{
  152. Secret: setting.SecretKey,
  153. Cookie: setting.CSRFCookieName,
  154. SetCookie: true,
  155. Header: "X-Csrf-Token",
  156. CookiePath: setting.AppSubUrl,
  157. }))
  158. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  159. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  160. &toolbox.HealthCheckFuncDesc{
  161. Desc: "Database connection",
  162. Func: models.Ping,
  163. },
  164. },
  165. }))
  166. m.Use(context.Contexter())
  167. return m
  168. }
  169. func runWeb(ctx *cli.Context) error {
  170. if ctx.IsSet("config") {
  171. setting.CustomConf = ctx.String("config")
  172. }
  173. routers.GlobalInit()
  174. checkVersion()
  175. m := newMacaron()
  176. reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
  177. ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
  178. ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
  179. reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
  180. bindIgnErr := binding.BindIgnErr
  181. // FIXME: not all routes need go through same middlewares.
  182. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  183. // Routers.
  184. m.Get("/", ignSignIn, routers.Home)
  185. m.Group("/explore", func() {
  186. m.Get("", func(ctx *context.Context) {
  187. ctx.Redirect(setting.AppSubUrl + "/explore/repos")
  188. })
  189. m.Get("/repos", routers.ExploreRepos)
  190. m.Get("/users", routers.ExploreUsers)
  191. }, ignSignIn)
  192. m.Combo("/install", routers.InstallInit).Get(routers.Install).
  193. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  194. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  195. // ***** START: User *****
  196. m.Group("/user", func() {
  197. m.Get("/login", user.SignIn)
  198. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  199. m.Get("/sign_up", user.SignUp)
  200. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  201. m.Get("/reset_password", user.ResetPasswd)
  202. m.Post("/reset_password", user.ResetPasswdPost)
  203. }, reqSignOut)
  204. m.Group("/user/settings", func() {
  205. m.Get("", user.Settings)
  206. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  207. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), user.SettingsAvatar)
  208. m.Post("/avatar/delete", user.SettingsDeleteAvatar)
  209. m.Combo("/email").Get(user.SettingsEmails).
  210. Post(bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  211. m.Post("/email/delete", user.DeleteEmail)
  212. m.Get("/password", user.SettingsPassword)
  213. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  214. m.Combo("/ssh").Get(user.SettingsSSHKeys).
  215. Post(bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  216. m.Post("/ssh/delete", user.DeleteSSHKey)
  217. m.Combo("/applications").Get(user.SettingsApplications).
  218. Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  219. m.Post("/applications/delete", user.SettingsDeleteApplication)
  220. m.Route("/delete", "GET,POST", user.SettingsDelete)
  221. }, reqSignIn, func(ctx *context.Context) {
  222. ctx.Data["PageIsUserSettings"] = true
  223. })
  224. m.Group("/user", func() {
  225. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  226. m.Any("/activate", user.Activate)
  227. m.Any("/activate_email", user.ActivateEmail)
  228. m.Get("/email2user", user.Email2User)
  229. m.Get("/forget_password", user.ForgotPasswd)
  230. m.Post("/forget_password", user.ForgotPasswdPost)
  231. m.Get("/logout", user.SignOut)
  232. })
  233. // ***** END: User *****
  234. adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  235. // ***** START: Admin *****
  236. m.Group("/admin", func() {
  237. m.Get("", adminReq, admin.Dashboard)
  238. m.Get("/config", admin.Config)
  239. m.Post("/config/test_mail", admin.SendTestMail)
  240. m.Get("/monitor", admin.Monitor)
  241. m.Group("/users", func() {
  242. m.Get("", admin.Users)
  243. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCrateUserForm{}), admin.NewUserPost)
  244. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  245. m.Post("/:userid/delete", admin.DeleteUser)
  246. })
  247. m.Group("/orgs", func() {
  248. m.Get("", admin.Organizations)
  249. })
  250. m.Group("/repos", func() {
  251. m.Get("", admin.Repos)
  252. m.Post("/delete", admin.DeleteRepo)
  253. })
  254. m.Group("/auths", func() {
  255. m.Get("", admin.Authentications)
  256. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  257. m.Combo("/:authid").Get(admin.EditAuthSource).
  258. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  259. m.Post("/:authid/delete", admin.DeleteAuthSource)
  260. })
  261. m.Group("/notices", func() {
  262. m.Get("", admin.Notices)
  263. m.Post("/delete", admin.DeleteNotices)
  264. m.Get("/empty", admin.EmptyNotices)
  265. })
  266. }, adminReq)
  267. // ***** END: Admin *****
  268. m.Group("", func() {
  269. m.Group("/:username", func() {
  270. m.Get("", user.Profile)
  271. m.Get("/followers", user.Followers)
  272. m.Get("/following", user.Following)
  273. m.Get("/stars", user.Stars)
  274. })
  275. m.Get("/attachments/:uuid", func(ctx *context.Context) {
  276. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  277. if err != nil {
  278. if models.IsErrAttachmentNotExist(err) {
  279. ctx.Error(404)
  280. } else {
  281. ctx.Handle(500, "GetAttachmentByUUID", err)
  282. }
  283. return
  284. }
  285. fr, err := os.Open(attach.LocalPath())
  286. if err != nil {
  287. ctx.Handle(500, "Open", err)
  288. return
  289. }
  290. defer fr.Close()
  291. ctx.Header().Set("Cache-Control", "public,max-age=86400")
  292. // Fix #312. Attachments with , in their name are not handled correctly by Google Chrome.
  293. // We must put the name in " manually.
  294. if err = repo.ServeData(ctx, "\""+attach.Name+"\"", fr); err != nil {
  295. ctx.Handle(500, "ServeData", err)
  296. return
  297. }
  298. })
  299. m.Post("/issues/attachments", repo.UploadIssueAttachment)
  300. }, ignSignIn)
  301. m.Group("/:username", func() {
  302. m.Get("/action/:action", user.Action)
  303. }, reqSignIn)
  304. if macaron.Env == macaron.DEV {
  305. m.Get("/template/*", dev.TemplatePreview)
  306. }
  307. reqRepoAdmin := context.RequireRepoAdmin()
  308. reqRepoWriter := context.RequireRepoWriter()
  309. // ***** START: Organization *****
  310. m.Group("/org", func() {
  311. m.Get("/create", org.Create)
  312. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  313. m.Group("/:org", func() {
  314. m.Get("/dashboard", user.Dashboard)
  315. m.Get("/^:type(issues|pulls)$", user.Issues)
  316. m.Get("/members", org.Members)
  317. m.Get("/members/action/:action", org.MembersAction)
  318. m.Get("/teams", org.Teams)
  319. }, context.OrgAssignment(true))
  320. m.Group("/:org", func() {
  321. m.Get("/teams/:team", org.TeamMembers)
  322. m.Get("/teams/:team/repositories", org.TeamRepositories)
  323. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  324. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  325. }, context.OrgAssignment(true, false, true))
  326. m.Group("/:org", func() {
  327. m.Get("/teams/new", org.NewTeam)
  328. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  329. m.Get("/teams/:team/edit", org.EditTeam)
  330. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  331. m.Post("/teams/:team/delete", org.DeleteTeam)
  332. m.Group("/settings", func() {
  333. m.Combo("").Get(org.Settings).
  334. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  335. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), org.SettingsAvatar)
  336. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  337. m.Group("/hooks", func() {
  338. m.Get("", org.Webhooks)
  339. m.Post("/delete", org.DeleteWebhook)
  340. m.Get("/:type/new", repo.WebhooksNew)
  341. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  342. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  343. m.Get("/:id", repo.WebHooksEdit)
  344. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  345. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  346. })
  347. m.Route("/delete", "GET,POST", org.SettingsDelete)
  348. })
  349. m.Route("/invitations/new", "GET,POST", org.Invitation)
  350. }, context.OrgAssignment(true, true))
  351. }, reqSignIn)
  352. // ***** END: Organization *****
  353. // ***** START: Repository *****
  354. m.Group("/repo", func() {
  355. m.Get("/create", repo.Create)
  356. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  357. m.Get("/migrate", repo.Migrate)
  358. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  359. m.Combo("/fork/:repoid").Get(repo.Fork).
  360. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  361. }, reqSignIn)
  362. m.Group("/:username/:reponame", func() {
  363. m.Group("/settings", func() {
  364. m.Combo("").Get(repo.Settings).
  365. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  366. m.Group("/collaboration", func() {
  367. m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
  368. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  369. m.Post("/delete", repo.DeleteCollaboration)
  370. })
  371. m.Group("/hooks", func() {
  372. m.Get("", repo.Webhooks)
  373. m.Post("/delete", repo.DeleteWebhook)
  374. m.Get("/:type/new", repo.WebhooksNew)
  375. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  376. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  377. m.Get("/:id", repo.WebHooksEdit)
  378. m.Post("/:id/test", repo.TestWebhook)
  379. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  380. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  381. m.Group("/git", func() {
  382. m.Get("", repo.GitHooks)
  383. m.Combo("/:name").Get(repo.GitHooksEdit).
  384. Post(repo.GitHooksEditPost)
  385. }, context.GitHookService())
  386. })
  387. m.Group("/keys", func() {
  388. m.Combo("").Get(repo.DeployKeys).
  389. Post(bindIgnErr(auth.AddSSHKeyForm{}), repo.DeployKeysPost)
  390. m.Post("/delete", repo.DeleteDeployKey)
  391. })
  392. }, func(ctx *context.Context) {
  393. ctx.Data["PageIsSettings"] = true
  394. })
  395. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
  396. m.Get("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  397. m.Group("/:username/:reponame", func() {
  398. m.Group("/issues", func() {
  399. m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
  400. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  401. m.Combo("/:index/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  402. m.Group("/:index", func() {
  403. m.Post("/label", repo.UpdateIssueLabel)
  404. m.Post("/milestone", repo.UpdateIssueMilestone)
  405. m.Post("/assignee", repo.UpdateIssueAssignee)
  406. }, reqRepoWriter)
  407. m.Group("/:index", func() {
  408. m.Post("/title", repo.UpdateIssueTitle)
  409. m.Post("/content", repo.UpdateIssueContent)
  410. })
  411. })
  412. m.Post("/comments/:id", repo.UpdateCommentContent)
  413. m.Group("/labels", func() {
  414. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  415. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  416. m.Post("/delete", repo.DeleteLabel)
  417. }, reqRepoWriter, context.RepoRef())
  418. m.Group("/milestones", func() {
  419. m.Combo("/new").Get(repo.NewMilestone).
  420. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  421. m.Get("/:id/edit", repo.EditMilestone)
  422. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  423. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  424. m.Post("/delete", repo.DeleteMilestone)
  425. }, reqRepoWriter, context.RepoRef())
  426. m.Group("/releases", func() {
  427. m.Get("/new", repo.NewRelease)
  428. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  429. m.Get("/edit/:tagname", repo.EditRelease)
  430. m.Post("/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  431. m.Post("/delete", repo.DeleteRelease)
  432. }, reqRepoWriter, context.RepoRef())
  433. m.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest).
  434. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  435. }, reqSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  436. m.Group("/:username/:reponame", func() {
  437. m.Group("", func() {
  438. m.Get("/releases", repo.Releases)
  439. m.Get("/^:type(issues|pulls)$", repo.RetrieveLabels, repo.Issues)
  440. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  441. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  442. m.Get("/milestones", repo.Milestones)
  443. }, context.RepoRef())
  444. // m.Get("/branches", repo.Branches)
  445. m.Group("/wiki", func() {
  446. m.Get("/?:page", repo.Wiki)
  447. m.Get("/_pages", repo.WikiPages)
  448. m.Group("", func() {
  449. m.Combo("/_new").Get(repo.NewWiki).
  450. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  451. m.Combo("/:page/_edit").Get(repo.EditWiki).
  452. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  453. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  454. }, reqSignIn, reqRepoWriter)
  455. }, repo.MustEnableWiki, context.RepoRef())
  456. m.Get("/archive/*", repo.Download)
  457. m.Group("/pulls/:index", func() {
  458. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  459. m.Get("/files", context.RepoRef(), repo.ViewPullFiles)
  460. m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  461. }, repo.MustAllowPulls)
  462. m.Group("", func() {
  463. m.Get("/src/*", repo.Home)
  464. m.Get("/raw/*", repo.SingleDownload)
  465. m.Get("/commits/*", repo.RefCommits)
  466. m.Get("/commit/:sha([a-z0-9]{40})$", repo.Diff)
  467. m.Get("/forks", repo.Forks)
  468. }, context.RepoRef())
  469. m.Get("/commit/:sha([a-z0-9]{40})\\.:ext(patch|diff)", repo.RawDiff)
  470. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.CompareDiff)
  471. }, ignSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  472. m.Group("/:username/:reponame", func() {
  473. m.Get("/stars", repo.Stars)
  474. m.Get("/watchers", repo.Watchers)
  475. }, ignSignIn, context.RepoAssignment(), context.RepoRef())
  476. m.Group("/:username", func() {
  477. m.Group("/:reponame", func() {
  478. m.Get("", repo.Home)
  479. m.Get("\\.git$", repo.Home)
  480. }, ignSignIn, context.RepoAssignment(true), context.RepoRef())
  481. m.Group("/:reponame", func() {
  482. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  483. m.Head("/tasks/trigger", repo.TriggerTask)
  484. })
  485. })
  486. // ***** END: Repository *****
  487. m.Group("/api", func() {
  488. apiv1.RegisterRoutes(m)
  489. }, ignSignIn)
  490. // robots.txt
  491. m.Get("/robots.txt", func(ctx *context.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. return nil
  523. }