web.go 19 KB

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