web.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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"},
  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.4"},
  81. {"github.com/gogits/git-module", git.Version, "0.3.3"},
  82. {"github.com/gogits/go-gogs-client", gogs.Version, "0.10.1"},
  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. funcMap := template.NewFuncMap()
  120. m.Use(macaron.Renderer(macaron.RenderOptions{
  121. Directory: path.Join(setting.StaticRootPath, "templates"),
  122. AppendDirectories: []string{path.Join(setting.CustomPath, "templates")},
  123. Funcs: funcMap,
  124. IndentJSON: macaron.Env != macaron.PROD,
  125. }))
  126. models.InitMailRender(path.Join(setting.StaticRootPath, "templates/mail"),
  127. path.Join(setting.CustomPath, "templates/mail"), funcMap)
  128. localeNames, err := bindata.AssetDir("conf/locale")
  129. if err != nil {
  130. log.Fatal(4, "Fail to list locale files: %v", err)
  131. }
  132. localFiles := make(map[string][]byte)
  133. for _, name := range localeNames {
  134. localFiles[name] = bindata.MustAsset("conf/locale/" + name)
  135. }
  136. m.Use(i18n.I18n(i18n.Options{
  137. SubURL: setting.AppSubUrl,
  138. Files: localFiles,
  139. CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
  140. Langs: setting.Langs,
  141. Names: setting.Names,
  142. DefaultLang: "en-US",
  143. Redirect: true,
  144. }))
  145. m.Use(cache.Cacher(cache.Options{
  146. Adapter: setting.CacheAdapter,
  147. AdapterConfig: setting.CacheConn,
  148. Interval: setting.CacheInternal,
  149. }))
  150. m.Use(captcha.Captchaer(captcha.Options{
  151. SubURL: setting.AppSubUrl,
  152. }))
  153. m.Use(session.Sessioner(setting.SessionConfig))
  154. m.Use(csrf.Csrfer(csrf.Options{
  155. Secret: setting.SecretKey,
  156. Cookie: setting.CSRFCookieName,
  157. SetCookie: true,
  158. Header: "X-Csrf-Token",
  159. CookiePath: setting.AppSubUrl,
  160. }))
  161. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  162. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  163. &toolbox.HealthCheckFuncDesc{
  164. Desc: "Database connection",
  165. Func: models.Ping,
  166. },
  167. },
  168. }))
  169. m.Use(context.Contexter())
  170. return m
  171. }
  172. func runWeb(ctx *cli.Context) error {
  173. if ctx.IsSet("config") {
  174. setting.CustomConf = ctx.String("config")
  175. }
  176. routers.GlobalInit()
  177. checkVersion()
  178. m := newMacaron()
  179. reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
  180. ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
  181. ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
  182. reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
  183. bindIgnErr := binding.BindIgnErr
  184. // FIXME: not all routes need go through same middlewares.
  185. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  186. // Routers.
  187. m.Get("/", ignSignIn, routers.Home)
  188. m.Group("/explore", func() {
  189. m.Get("", func(ctx *context.Context) {
  190. ctx.Redirect(setting.AppSubUrl + "/explore/repos")
  191. })
  192. m.Get("/repos", routers.ExploreRepos)
  193. m.Get("/users", routers.ExploreUsers)
  194. }, ignSignIn)
  195. m.Combo("/install", routers.InstallInit).Get(routers.Install).
  196. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  197. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  198. // ***** START: User *****
  199. m.Group("/user", func() {
  200. m.Get("/login", user.SignIn)
  201. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  202. m.Get("/sign_up", user.SignUp)
  203. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  204. m.Get("/reset_password", user.ResetPasswd)
  205. m.Post("/reset_password", user.ResetPasswdPost)
  206. }, reqSignOut)
  207. m.Group("/user/settings", func() {
  208. m.Get("", user.Settings)
  209. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  210. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), user.SettingsAvatar)
  211. m.Post("/avatar/delete", user.SettingsDeleteAvatar)
  212. m.Combo("/email").Get(user.SettingsEmails).
  213. Post(bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  214. m.Post("/email/delete", user.DeleteEmail)
  215. m.Get("/password", user.SettingsPassword)
  216. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  217. m.Combo("/ssh").Get(user.SettingsSSHKeys).
  218. Post(bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  219. m.Post("/ssh/delete", user.DeleteSSHKey)
  220. m.Combo("/applications").Get(user.SettingsApplications).
  221. Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  222. m.Post("/applications/delete", user.SettingsDeleteApplication)
  223. m.Route("/delete", "GET,POST", user.SettingsDelete)
  224. }, reqSignIn, func(ctx *context.Context) {
  225. ctx.Data["PageIsUserSettings"] = true
  226. })
  227. m.Group("/user", func() {
  228. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  229. m.Any("/activate", user.Activate)
  230. m.Any("/activate_email", user.ActivateEmail)
  231. m.Get("/email2user", user.Email2User)
  232. m.Get("/forget_password", user.ForgotPasswd)
  233. m.Post("/forget_password", user.ForgotPasswdPost)
  234. m.Get("/logout", user.SignOut)
  235. })
  236. // ***** END: User *****
  237. adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  238. // ***** START: Admin *****
  239. m.Group("/admin", func() {
  240. m.Get("", adminReq, admin.Dashboard)
  241. m.Get("/config", admin.Config)
  242. m.Post("/config/test_mail", admin.SendTestMail)
  243. m.Get("/monitor", admin.Monitor)
  244. m.Group("/users", func() {
  245. m.Get("", admin.Users)
  246. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCrateUserForm{}), admin.NewUserPost)
  247. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  248. m.Post("/:userid/delete", admin.DeleteUser)
  249. })
  250. m.Group("/orgs", func() {
  251. m.Get("", admin.Organizations)
  252. })
  253. m.Group("/repos", func() {
  254. m.Get("", admin.Repos)
  255. m.Post("/delete", admin.DeleteRepo)
  256. })
  257. m.Group("/auths", func() {
  258. m.Get("", admin.Authentications)
  259. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  260. m.Combo("/:authid").Get(admin.EditAuthSource).
  261. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  262. m.Post("/:authid/delete", admin.DeleteAuthSource)
  263. })
  264. m.Group("/notices", func() {
  265. m.Get("", admin.Notices)
  266. m.Post("/delete", admin.DeleteNotices)
  267. m.Get("/empty", admin.EmptyNotices)
  268. })
  269. }, adminReq)
  270. // ***** END: Admin *****
  271. m.Group("", func() {
  272. m.Group("/:username", func() {
  273. m.Get("", user.Profile)
  274. m.Get("/followers", user.Followers)
  275. m.Get("/following", user.Following)
  276. m.Get("/stars", user.Stars)
  277. })
  278. m.Get("/attachments/:uuid", func(ctx *context.Context) {
  279. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  280. if err != nil {
  281. if models.IsErrAttachmentNotExist(err) {
  282. ctx.Error(404)
  283. } else {
  284. ctx.Handle(500, "GetAttachmentByUUID", err)
  285. }
  286. return
  287. }
  288. fr, err := os.Open(attach.LocalPath())
  289. if err != nil {
  290. ctx.Handle(500, "Open", err)
  291. return
  292. }
  293. defer fr.Close()
  294. ctx.Header().Set("Cache-Control", "public,max-age=86400")
  295. // Fix #312. Attachments with , in their name are not handled correctly by Google Chrome.
  296. // We must put the name in " manually.
  297. if err = repo.ServeData(ctx, "\""+attach.Name+"\"", fr); err != nil {
  298. ctx.Handle(500, "ServeData", err)
  299. return
  300. }
  301. })
  302. m.Post("/issues/attachments", repo.UploadIssueAttachment)
  303. }, ignSignIn)
  304. m.Group("/:username", func() {
  305. m.Get("/action/:action", user.Action)
  306. }, reqSignIn)
  307. if macaron.Env == macaron.DEV {
  308. m.Get("/template/*", dev.TemplatePreview)
  309. }
  310. reqRepoAdmin := context.RequireRepoAdmin()
  311. reqRepoWriter := context.RequireRepoWriter()
  312. // ***** START: Organization *****
  313. m.Group("/org", func() {
  314. m.Get("/create", org.Create)
  315. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  316. m.Group("/:org", func() {
  317. m.Get("/dashboard", user.Dashboard)
  318. m.Get("/^:type(issues|pulls)$", user.Issues)
  319. m.Get("/members", org.Members)
  320. m.Get("/members/action/:action", org.MembersAction)
  321. m.Get("/teams", org.Teams)
  322. }, context.OrgAssignment(true))
  323. m.Group("/:org", func() {
  324. m.Get("/teams/:team", org.TeamMembers)
  325. m.Get("/teams/:team/repositories", org.TeamRepositories)
  326. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  327. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  328. }, context.OrgAssignment(true, false, true))
  329. m.Group("/:org", func() {
  330. m.Get("/teams/new", org.NewTeam)
  331. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  332. m.Get("/teams/:team/edit", org.EditTeam)
  333. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  334. m.Post("/teams/:team/delete", org.DeleteTeam)
  335. m.Group("/settings", func() {
  336. m.Combo("").Get(org.Settings).
  337. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  338. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), org.SettingsAvatar)
  339. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  340. m.Group("/hooks", func() {
  341. m.Get("", org.Webhooks)
  342. m.Post("/delete", org.DeleteWebhook)
  343. m.Get("/:type/new", repo.WebhooksNew)
  344. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  345. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  346. m.Get("/:id", repo.WebHooksEdit)
  347. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  348. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  349. })
  350. m.Route("/delete", "GET,POST", org.SettingsDelete)
  351. })
  352. m.Route("/invitations/new", "GET,POST", org.Invitation)
  353. }, context.OrgAssignment(true, true))
  354. }, reqSignIn)
  355. // ***** END: Organization *****
  356. // ***** START: Repository *****
  357. m.Group("/repo", func() {
  358. m.Get("/create", repo.Create)
  359. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  360. m.Get("/migrate", repo.Migrate)
  361. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  362. m.Combo("/fork/:repoid").Get(repo.Fork).
  363. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  364. }, reqSignIn)
  365. m.Group("/:username/:reponame", func() {
  366. m.Group("/settings", func() {
  367. m.Combo("").Get(repo.Settings).
  368. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  369. m.Group("/collaboration", func() {
  370. m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
  371. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  372. m.Post("/delete", repo.DeleteCollaboration)
  373. })
  374. m.Group("/hooks", func() {
  375. m.Get("", repo.Webhooks)
  376. m.Post("/delete", repo.DeleteWebhook)
  377. m.Get("/:type/new", repo.WebhooksNew)
  378. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  379. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  380. m.Get("/:id", repo.WebHooksEdit)
  381. m.Post("/:id/test", repo.TestWebhook)
  382. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  383. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  384. m.Group("/git", func() {
  385. m.Get("", repo.GitHooks)
  386. m.Combo("/:name").Get(repo.GitHooksEdit).
  387. Post(repo.GitHooksEditPost)
  388. }, context.GitHookService())
  389. })
  390. m.Group("/keys", func() {
  391. m.Combo("").Get(repo.DeployKeys).
  392. Post(bindIgnErr(auth.AddSSHKeyForm{}), repo.DeployKeysPost)
  393. m.Post("/delete", repo.DeleteDeployKey)
  394. })
  395. }, func(ctx *context.Context) {
  396. ctx.Data["PageIsSettings"] = true
  397. })
  398. }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
  399. m.Get("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
  400. m.Group("/:username/:reponame", func() {
  401. m.Group("/issues", func() {
  402. m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
  403. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  404. m.Combo("/:index/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  405. m.Group("/:index", func() {
  406. m.Post("/label", repo.UpdateIssueLabel)
  407. m.Post("/milestone", repo.UpdateIssueMilestone)
  408. m.Post("/assignee", repo.UpdateIssueAssignee)
  409. }, reqRepoWriter)
  410. m.Group("/:index", func() {
  411. m.Post("/title", repo.UpdateIssueTitle)
  412. m.Post("/content", repo.UpdateIssueContent)
  413. })
  414. })
  415. m.Group("/comments/:id", func() {
  416. m.Post("", repo.UpdateCommentContent)
  417. m.Post("/delete", repo.DeleteComment)
  418. })
  419. m.Group("/labels", func() {
  420. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  421. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  422. m.Post("/delete", repo.DeleteLabel)
  423. }, reqRepoWriter, context.RepoRef())
  424. m.Group("/milestones", func() {
  425. m.Combo("/new").Get(repo.NewMilestone).
  426. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  427. m.Get("/:id/edit", repo.EditMilestone)
  428. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  429. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  430. m.Post("/delete", repo.DeleteMilestone)
  431. }, reqRepoWriter, context.RepoRef())
  432. m.Group("/releases", func() {
  433. m.Get("/new", repo.NewRelease)
  434. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  435. m.Get("/edit/:tagname", repo.EditRelease)
  436. m.Post("/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  437. m.Post("/delete", repo.DeleteRelease)
  438. }, reqRepoWriter, context.RepoRef())
  439. m.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest).
  440. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  441. }, reqSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  442. m.Group("/:username/:reponame", func() {
  443. m.Group("", func() {
  444. m.Get("/releases", repo.Releases)
  445. m.Get("/^:type(issues|pulls)$", repo.RetrieveLabels, repo.Issues)
  446. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  447. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  448. m.Get("/milestones", repo.Milestones)
  449. }, context.RepoRef())
  450. // m.Get("/branches", repo.Branches)
  451. m.Group("/wiki", func() {
  452. m.Get("/?:page", repo.Wiki)
  453. m.Get("/_pages", repo.WikiPages)
  454. m.Group("", func() {
  455. m.Combo("/_new").Get(repo.NewWiki).
  456. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  457. m.Combo("/:page/_edit").Get(repo.EditWiki).
  458. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  459. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  460. }, reqSignIn, reqRepoWriter)
  461. }, repo.MustEnableWiki, context.RepoRef())
  462. m.Get("/archive/*", repo.Download)
  463. m.Group("/pulls/:index", func() {
  464. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  465. m.Get("/files", context.RepoRef(), repo.ViewPullFiles)
  466. m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
  467. }, repo.MustAllowPulls)
  468. m.Group("", func() {
  469. m.Get("/src/*", repo.Home)
  470. m.Get("/raw/*", repo.SingleDownload)
  471. m.Get("/commits/*", repo.RefCommits)
  472. m.Get("/commit/:sha([a-z0-9]{40})$", repo.Diff)
  473. m.Get("/forks", repo.Forks)
  474. }, context.RepoRef())
  475. m.Get("/commit/:sha([a-z0-9]{40})\\.:ext(patch|diff)", repo.RawDiff)
  476. m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.CompareDiff)
  477. }, ignSignIn, context.RepoAssignment(), repo.MustBeNotBare)
  478. m.Group("/:username/:reponame", func() {
  479. m.Get("/stars", repo.Stars)
  480. m.Get("/watchers", repo.Watchers)
  481. }, ignSignIn, context.RepoAssignment(), context.RepoRef())
  482. m.Group("/:username", func() {
  483. m.Group("/:reponame", func() {
  484. m.Get("", repo.Home)
  485. m.Get("\\.git$", repo.Home)
  486. }, ignSignIn, context.RepoAssignment(true), context.RepoRef())
  487. m.Group("/:reponame", func() {
  488. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  489. m.Head("/tasks/trigger", repo.TriggerTask)
  490. })
  491. })
  492. // ***** END: Repository *****
  493. m.Group("/api", func() {
  494. apiv1.RegisterRoutes(m)
  495. }, ignSignIn)
  496. // robots.txt
  497. m.Get("/robots.txt", func(ctx *context.Context) {
  498. if setting.HasRobotsTxt {
  499. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  500. } else {
  501. ctx.Error(404)
  502. }
  503. })
  504. // Not found handler.
  505. m.NotFound(routers.NotFound)
  506. // Flag for port number in case first time run conflict.
  507. if ctx.IsSet("port") {
  508. setting.AppUrl = strings.Replace(setting.AppUrl, setting.HttpPort, ctx.String("port"), 1)
  509. setting.HttpPort = ctx.String("port")
  510. }
  511. var err error
  512. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  513. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  514. switch setting.Protocol {
  515. case setting.HTTP:
  516. err = http.ListenAndServe(listenAddr, m)
  517. case setting.HTTPS:
  518. server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS10}, Handler: m}
  519. err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  520. case setting.FCGI:
  521. err = fcgi.Serve(nil, m)
  522. default:
  523. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  524. }
  525. if err != nil {
  526. log.Fatal(4, "Fail to start server: %v", err)
  527. }
  528. return nil
  529. }