web.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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-shell", git.Version, "0.2.1"},
  84. {"github.com/gogits/go-gogs-client", gogs.Version, "0.7.2"},
  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. m.Get("/teams/:team", org.TeamMembers)
  316. m.Get("/teams/:team/repositories", org.TeamRepositories)
  317. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  318. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  319. }, middleware.OrgAssignment(true))
  320. m.Group("/:org", func() {
  321. m.Get("/teams/new", org.NewTeam)
  322. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  323. m.Get("/teams/:team/edit", org.EditTeam)
  324. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  325. m.Post("/teams/:team/delete", org.DeleteTeam)
  326. m.Group("/settings", func() {
  327. m.Combo("").Get(org.Settings).
  328. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  329. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), org.SettingsAvatar)
  330. m.Group("/hooks", func() {
  331. m.Get("", org.Webhooks)
  332. m.Post("/delete", org.DeleteWebhook)
  333. m.Get("/:type/new", repo.WebhooksNew)
  334. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  335. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  336. m.Get("/:id", repo.WebHooksEdit)
  337. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  338. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  339. })
  340. m.Route("/delete", "GET,POST", org.SettingsDelete)
  341. })
  342. m.Route("/invitations/new", "GET,POST", org.Invitation)
  343. }, middleware.OrgAssignment(true, true))
  344. }, reqSignIn)
  345. // ***** END: Organization *****
  346. // ***** START: Repository *****
  347. m.Group("/repo", func() {
  348. m.Get("/create", repo.Create)
  349. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  350. m.Get("/migrate", repo.Migrate)
  351. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  352. m.Combo("/fork/:repoid").Get(repo.Fork).
  353. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  354. }, reqSignIn)
  355. m.Group("/:username/:reponame", func() {
  356. m.Group("/settings", func() {
  357. m.Combo("").Get(repo.Settings).
  358. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  359. m.Route("/collaboration", "GET,POST", repo.Collaboration)
  360. m.Group("/hooks", func() {
  361. m.Get("", repo.Webhooks)
  362. m.Post("/delete", repo.DeleteWebhook)
  363. m.Get("/:type/new", repo.WebhooksNew)
  364. m.Post("/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  365. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  366. m.Get("/:id", repo.WebHooksEdit)
  367. m.Post("/:id/test", repo.TestWebhook)
  368. m.Post("/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  369. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  370. m.Group("/git", func() {
  371. m.Get("", repo.GitHooks)
  372. m.Combo("/:name").Get(repo.GitHooksEdit).
  373. Post(repo.GitHooksEditPost)
  374. }, middleware.GitHookService())
  375. })
  376. m.Group("/keys", func() {
  377. m.Combo("").Get(repo.DeployKeys).
  378. Post(bindIgnErr(auth.AddSSHKeyForm{}), repo.DeployKeysPost)
  379. m.Post("/delete", repo.DeleteDeployKey)
  380. })
  381. }, func(ctx *middleware.Context) {
  382. ctx.Data["PageIsSettings"] = true
  383. })
  384. }, reqSignIn, middleware.RepoAssignment(), reqRepoAdmin, middleware.RepoRef())
  385. m.Group("/:username/:reponame", func() {
  386. m.Get("/action/:action", repo.Action)
  387. m.Group("/issues", func() {
  388. m.Combo("/new", repo.MustEnableIssues).Get(middleware.RepoRef(), repo.NewIssue).
  389. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  390. m.Combo("/:index/comments").Post(bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  391. m.Group("/:index", func() {
  392. m.Post("/label", repo.UpdateIssueLabel)
  393. m.Post("/milestone", repo.UpdateIssueMilestone)
  394. m.Post("/assignee", repo.UpdateIssueAssignee)
  395. }, reqRepoAdmin)
  396. m.Group("/:index", func() {
  397. m.Post("/title", repo.UpdateIssueTitle)
  398. m.Post("/content", repo.UpdateIssueContent)
  399. })
  400. })
  401. m.Post("/comments/:id", repo.UpdateCommentContent)
  402. m.Group("/labels", func() {
  403. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  404. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  405. m.Post("/delete", repo.DeleteLabel)
  406. }, reqRepoAdmin, middleware.RepoRef())
  407. m.Group("/milestones", func() {
  408. m.Combo("/new").Get(repo.NewMilestone).
  409. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  410. m.Get("/:id/edit", repo.EditMilestone)
  411. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  412. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  413. m.Post("/delete", repo.DeleteMilestone)
  414. }, reqRepoAdmin, middleware.RepoRef())
  415. m.Group("/releases", func() {
  416. m.Get("/new", repo.NewRelease)
  417. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  418. m.Get("/edit/:tagname", repo.EditRelease)
  419. m.Post("/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  420. m.Post("/delete", repo.DeleteRelease)
  421. }, reqRepoAdmin, middleware.RepoRef())
  422. m.Combo("/compare/*", repo.MustEnablePulls).Get(repo.CompareAndPullRequest).
  423. Post(bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  424. }, reqSignIn, middleware.RepoAssignment())
  425. m.Group("/:username/:reponame", func() {
  426. m.Group("", func() {
  427. m.Get("/releases", repo.Releases)
  428. m.Get("/^:type(issues|pulls)$", repo.RetrieveLabels, repo.Issues)
  429. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  430. m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
  431. m.Get("/milestones", repo.Milestones)
  432. }, middleware.RepoRef())
  433. // m.Get("/branches", repo.Branches)
  434. m.Group("/wiki", func() {
  435. m.Get("/?:page", repo.Wiki)
  436. m.Get("/_pages", repo.WikiPages)
  437. m.Group("", func() {
  438. m.Combo("/_new").Get(repo.NewWiki).
  439. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  440. m.Combo("/:page/_edit").Get(repo.EditWiki).
  441. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  442. }, reqSignIn, reqRepoPusher)
  443. }, repo.MustEnableWiki, middleware.RepoRef())
  444. m.Get("/archive/*", repo.Download)
  445. m.Group("/pulls/:index", func() {
  446. m.Get("/commits", middleware.RepoRef(), repo.ViewPullCommits)
  447. m.Get("/files", middleware.RepoRef(), repo.ViewPullFiles)
  448. m.Post("/merge", reqRepoAdmin, repo.MergePullRequest)
  449. }, repo.MustEnablePulls)
  450. m.Group("", func() {
  451. m.Get("/src/*", repo.Home)
  452. m.Get("/raw/*", repo.SingleDownload)
  453. m.Get("/commits/*", repo.RefCommits)
  454. m.Get("/commit/*", repo.Diff)
  455. m.Get("/stars", repo.Stars)
  456. m.Get("/watchers", repo.Watchers)
  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())
  461. m.Group("/:username", func() {
  462. m.Group("/:reponame", func() {
  463. m.Get("", repo.Home)
  464. m.Get("\\.git$", repo.Home)
  465. }, ignSignIn, middleware.RepoAssignment(true), middleware.RepoRef())
  466. m.Group("/:reponame", func() {
  467. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  468. m.Head("/tasks/trigger", repo.TriggerTask)
  469. })
  470. })
  471. // ***** END: Repository *****
  472. // robots.txt
  473. m.Get("/robots.txt", func(ctx *middleware.Context) {
  474. if setting.HasRobotsTxt {
  475. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  476. } else {
  477. ctx.Error(404)
  478. }
  479. })
  480. // Not found handler.
  481. m.NotFound(routers.NotFound)
  482. // Flag for port number in case first time run conflict.
  483. if ctx.IsSet("port") {
  484. setting.AppUrl = strings.Replace(setting.AppUrl, setting.HttpPort, ctx.String("port"), 1)
  485. setting.HttpPort = ctx.String("port")
  486. }
  487. var err error
  488. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  489. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  490. switch setting.Protocol {
  491. case setting.HTTP:
  492. err = http.ListenAndServe(listenAddr, m)
  493. case setting.HTTPS:
  494. server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS10}, Handler: m}
  495. err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  496. case setting.FCGI:
  497. err = fcgi.Serve(nil, m)
  498. default:
  499. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  500. }
  501. if err != nil {
  502. log.Fatal(4, "Fail to start server: %v", err)
  503. }
  504. }