You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

web.go 20KB

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