web.go 19 KB

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