Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

web.go 19KB

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