web.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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/macaron-contrib/binding"
  18. "github.com/macaron-contrib/cache"
  19. "github.com/macaron-contrib/captcha"
  20. "github.com/macaron-contrib/csrf"
  21. "github.com/macaron-contrib/i18n"
  22. "github.com/macaron-contrib/oauth2"
  23. "github.com/macaron-contrib/session"
  24. "github.com/macaron-contrib/toolbox"
  25. "gopkg.in/ini.v1"
  26. api "github.com/gogits/go-gogs-client"
  27. "github.com/gogits/gogs/models"
  28. "github.com/gogits/gogs/modules/auth"
  29. "github.com/gogits/gogs/modules/auth/apiv1"
  30. "github.com/gogits/gogs/modules/avatar"
  31. "github.com/gogits/gogs/modules/base"
  32. "github.com/gogits/gogs/modules/bindata"
  33. "github.com/gogits/gogs/modules/git"
  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/routers"
  38. "github.com/gogits/gogs/routers/admin"
  39. "github.com/gogits/gogs/routers/api/v1"
  40. "github.com/gogits/gogs/routers/dev"
  41. "github.com/gogits/gogs/routers/org"
  42. "github.com/gogits/gogs/routers/repo"
  43. "github.com/gogits/gogs/routers/user"
  44. )
  45. var CmdWeb = cli.Command{
  46. Name: "web",
  47. Usage: "Start Gogs web server",
  48. Description: `Gogs web server is the only thing you need to run,
  49. and it takes care of all the other things for you`,
  50. Action: runWeb,
  51. Flags: []cli.Flag{
  52. cli.StringFlag{"port, p", "3000", "Temporary port number to prevent conflict", ""},
  53. cli.StringFlag{"config, c", "custom/conf/app.ini", "Custom configuration file path", ""},
  54. },
  55. }
  56. type VerChecker struct {
  57. ImportPath string
  58. Version func() string
  59. Expected string
  60. }
  61. // checkVersion checks if binary matches the version of templates files.
  62. func checkVersion() {
  63. // Templates.
  64. data, err := ioutil.ReadFile(path.Join(setting.StaticRootPath, "templates/.VERSION"))
  65. if err != nil {
  66. log.Fatal(4, "Fail to read 'templates/.VERSION': %v", err)
  67. }
  68. if strings.TrimSpace(string(data)) != setting.AppVer {
  69. log.Fatal(4, "Binary and template file version does not match, did you forget to recompile?")
  70. }
  71. // Check dependency version.
  72. checkers := []VerChecker{
  73. {"github.com/Unknwon/macaron", macaron.Version, "0.5.4"},
  74. {"github.com/macaron-contrib/binding", binding.Version, "0.0.6"},
  75. {"github.com/macaron-contrib/cache", cache.Version, "0.0.7"},
  76. {"github.com/macaron-contrib/csrf", csrf.Version, "0.0.3"},
  77. {"github.com/macaron-contrib/i18n", i18n.Version, "0.0.7"},
  78. {"github.com/macaron-contrib/session", session.Version, "0.1.6"},
  79. {"gopkg.in/ini.v1", ini.Version, "1.2.0"},
  80. }
  81. for _, c := range checkers {
  82. ver := strings.Join(strings.Split(c.Version(), ".")[:3], ".")
  83. if git.MustParseVersion(ver).LessThan(git.MustParseVersion(c.Expected)) {
  84. log.Fatal(4, "Package '%s' version is too old(%s -> %s), did you forget to update?", c.ImportPath, ver, c.Expected)
  85. }
  86. }
  87. }
  88. // newMacaron initializes Macaron instance.
  89. func newMacaron() *macaron.Macaron {
  90. m := macaron.New()
  91. m.Use(macaron.Logger())
  92. m.Use(macaron.Recovery())
  93. if setting.EnableGzip {
  94. m.Use(macaron.Gziper())
  95. }
  96. if setting.Protocol == setting.FCGI {
  97. m.SetURLPrefix(setting.AppSubUrl)
  98. }
  99. m.Use(macaron.Static(
  100. path.Join(setting.StaticRootPath, "public"),
  101. macaron.StaticOptions{
  102. SkipLogging: !setting.DisableRouterLog,
  103. },
  104. ))
  105. m.Use(macaron.Static(
  106. setting.AvatarUploadPath,
  107. macaron.StaticOptions{
  108. Prefix: "avatars",
  109. SkipLogging: !setting.DisableRouterLog,
  110. },
  111. ))
  112. m.Use(macaron.Renderer(macaron.RenderOptions{
  113. Directory: path.Join(setting.StaticRootPath, "templates"),
  114. Funcs: []template.FuncMap{base.TemplateFuncs},
  115. IndentJSON: macaron.Env != macaron.PROD,
  116. }))
  117. localeNames, err := bindata.AssetDir("conf/locale")
  118. if err != nil {
  119. log.Fatal(4, "Fail to list locale files: %v", err)
  120. }
  121. localFiles := make(map[string][]byte)
  122. for _, name := range localeNames {
  123. localFiles[name] = bindata.MustAsset("conf/locale/" + name)
  124. }
  125. m.Use(i18n.I18n(i18n.Options{
  126. SubURL: setting.AppSubUrl,
  127. Files: localFiles,
  128. CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
  129. Langs: setting.Langs,
  130. Names: setting.Names,
  131. Redirect: true,
  132. }))
  133. m.Use(cache.Cacher(cache.Options{
  134. Adapter: setting.CacheAdapter,
  135. AdapterConfig: setting.CacheConn,
  136. Interval: setting.CacheInternal,
  137. }))
  138. m.Use(captcha.Captchaer(captcha.Options{
  139. SubURL: setting.AppSubUrl,
  140. }))
  141. m.Use(session.Sessioner(setting.SessionConfig))
  142. m.Use(csrf.Csrfer(csrf.Options{
  143. Secret: setting.SecretKey,
  144. SetCookie: true,
  145. Header: "X-Csrf-Token",
  146. CookiePath: setting.AppSubUrl,
  147. }))
  148. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  149. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  150. &toolbox.HealthCheckFuncDesc{
  151. Desc: "Database connection",
  152. Func: models.Ping,
  153. },
  154. },
  155. }))
  156. // OAuth 2.
  157. if setting.OauthService != nil {
  158. for _, info := range setting.OauthService.OauthInfos {
  159. m.Use(oauth2.NewOAuth2Provider(info.Options, info.AuthUrl, info.TokenUrl))
  160. }
  161. }
  162. m.Use(middleware.Contexter())
  163. return m
  164. }
  165. func runWeb(ctx *cli.Context) {
  166. if ctx.IsSet("config") {
  167. setting.CustomConf = ctx.String("config")
  168. }
  169. routers.GlobalInit()
  170. checkVersion()
  171. m := newMacaron()
  172. reqSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true})
  173. ignSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: setting.Service.RequireSignInView})
  174. ignSignInAndCsrf := middleware.Toggle(&middleware.ToggleOptions{DisableCsrf: true})
  175. reqSignOut := middleware.Toggle(&middleware.ToggleOptions{SignOutRequire: true})
  176. bind := binding.Bind
  177. bindIgnErr := binding.BindIgnErr
  178. // Routers.
  179. m.Get("/", ignSignIn, routers.Home)
  180. m.Get("/explore", ignSignIn, routers.Explore)
  181. m.Get("/help", ignSignIn, routers.Help)
  182. m.Get("/about", ignSignIn, routers.About)
  183. m.Get("/tos", ignSignIn, routers.Tos)
  184. m.Get("/outages", ignSignIn, routers.Outages)
  185. m.Combo("/install", routers.InstallInit).
  186. Get(routers.Install).
  187. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  188. m.Group("", func() {
  189. m.Get("/pulls", user.Pulls)
  190. m.Get("/issues", user.Issues)
  191. }, reqSignIn)
  192. // API.
  193. // FIXME: custom form error response.
  194. m.Group("/api", func() {
  195. m.Group("/v1", func() {
  196. // Miscellaneous.
  197. m.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown)
  198. m.Post("/markdown/raw", v1.MarkdownRaw)
  199. // Users.
  200. m.Group("/users", func() {
  201. m.Get("/search", v1.SearchUsers)
  202. m.Group("/:username", func() {
  203. m.Get("", v1.GetUserInfo)
  204. m.Group("/tokens", func() {
  205. m.Combo("").Get(v1.ListAccessTokens).Post(bind(v1.CreateAccessTokenForm{}), v1.CreateAccessToken)
  206. }, middleware.ApiReqBasicAuth())
  207. })
  208. })
  209. // Repositories.
  210. m.Combo("/user/repos", middleware.ApiReqToken()).Get(v1.ListMyRepos).Post(bind(api.CreateRepoOption{}), v1.CreateRepo)
  211. m.Post("/org/:org/repos", middleware.ApiReqToken(), bind(api.CreateRepoOption{}), v1.CreateOrgRepo)
  212. m.Group("/repos", func() {
  213. m.Get("/search", v1.SearchRepos)
  214. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), v1.MigrateRepo)
  215. m.Group("/:username/:reponame", func() {
  216. m.Combo("/hooks").Get(v1.ListRepoHooks).Post(bind(api.CreateHookOption{}), v1.CreateRepoHook)
  217. m.Patch("/hooks/:id:int", bind(api.EditHookOption{}), v1.EditRepoHook)
  218. m.Get("/raw/*", middleware.RepoRef(), v1.GetRepoRawFile)
  219. }, middleware.ApiRepoAssignment(), middleware.ApiReqToken())
  220. })
  221. m.Any("/*", func(ctx *middleware.Context) {
  222. ctx.HandleAPI(404, "Page not found")
  223. })
  224. })
  225. })
  226. // User.
  227. m.Group("/user", func() {
  228. m.Get("/login", user.SignIn)
  229. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  230. m.Get("/info/:name", user.SocialSignIn)
  231. m.Get("/sign_up", user.SignUp)
  232. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  233. m.Get("/reset_password", user.ResetPasswd)
  234. m.Post("/reset_password", user.ResetPasswdPost)
  235. }, reqSignOut)
  236. m.Group("/user/settings", func() {
  237. m.Get("", user.Settings)
  238. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
  239. m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), user.SettingsAvatar)
  240. m.Get("/email", user.SettingsEmails)
  241. m.Post("/email", bindIgnErr(auth.AddEmailForm{}), user.SettingsEmailPost)
  242. m.Get("/password", user.SettingsPassword)
  243. m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
  244. m.Get("/ssh", user.SettingsSSHKeys)
  245. m.Post("/ssh", bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
  246. m.Get("/social", user.SettingsSocial)
  247. m.Combo("/applications").Get(user.SettingsApplications).Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
  248. m.Route("/delete", "GET,POST", user.SettingsDelete)
  249. }, reqSignIn)
  250. m.Group("/user", func() {
  251. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  252. m.Any("/activate", user.Activate)
  253. m.Any("/activate_email", user.ActivateEmail)
  254. m.Get("/email2user", user.Email2User)
  255. m.Get("/forget_password", user.ForgotPasswd)
  256. m.Post("/forget_password", user.ForgotPasswdPost)
  257. m.Get("/logout", user.SignOut)
  258. })
  259. // Gravatar service.
  260. avt := avatar.CacheServer("public/img/avatar/", "public/img/avatar_default.jpg")
  261. os.MkdirAll("public/img/avatar/", os.ModePerm)
  262. m.Get("/avatar/:hash", avt.ServeHTTP)
  263. adminReq := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true, AdminRequire: true})
  264. m.Group("/admin", func() {
  265. m.Get("", adminReq, admin.Dashboard)
  266. m.Get("/config", admin.Config)
  267. m.Get("/monitor", admin.Monitor)
  268. m.Group("/users", func() {
  269. m.Get("", admin.Users)
  270. m.Get("/new", admin.NewUser)
  271. m.Post("/new", bindIgnErr(auth.RegisterForm{}), admin.NewUserPost)
  272. m.Get("/:userid", admin.EditUser)
  273. m.Post("/:userid", bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  274. m.Post("/:userid/delete", admin.DeleteUser)
  275. })
  276. m.Group("/orgs", func() {
  277. m.Get("", admin.Organizations)
  278. })
  279. m.Group("/repos", func() {
  280. m.Get("", admin.Repositories)
  281. })
  282. m.Group("/auths", func() {
  283. m.Get("", admin.Authentications)
  284. m.Get("/new", admin.NewAuthSource)
  285. m.Post("/new", bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  286. m.Get("/:authid", admin.EditAuthSource)
  287. m.Post("/:authid", bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  288. m.Post("/:authid/delete", admin.DeleteAuthSource)
  289. })
  290. m.Group("/notices", func() {
  291. m.Get("", admin.Notices)
  292. m.Get("/:id:int/delete", admin.DeleteNotice)
  293. })
  294. }, adminReq)
  295. m.Get("/:username", ignSignIn, user.Profile)
  296. if macaron.Env == macaron.DEV {
  297. m.Get("/template/*", dev.TemplatePreview)
  298. }
  299. reqAdmin := middleware.RequireAdmin()
  300. // Organization.
  301. m.Group("/org", func() {
  302. m.Get("/create", org.Create)
  303. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  304. m.Group("/:org", func() {
  305. m.Get("/dashboard", user.Dashboard)
  306. m.Get("/members", org.Members)
  307. m.Get("/members/action/:action", org.MembersAction)
  308. m.Get("/teams", org.Teams)
  309. m.Get("/teams/:team", org.TeamMembers)
  310. m.Get("/teams/:team/repositories", org.TeamRepositories)
  311. m.Get("/teams/:team/action/:action", org.TeamsAction)
  312. m.Get("/teams/:team/action/repo/:action", org.TeamsRepoAction)
  313. }, middleware.OrgAssignment(true, true))
  314. m.Group("/:org", func() {
  315. m.Get("/teams/new", org.NewTeam)
  316. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  317. m.Get("/teams/:team/edit", org.EditTeam)
  318. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  319. m.Post("/teams/:team/delete", org.DeleteTeam)
  320. m.Group("/settings", func() {
  321. m.Get("", org.Settings)
  322. m.Post("", bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  323. m.Get("/hooks", org.SettingsHooks)
  324. m.Get("/hooks/new", repo.WebHooksNew)
  325. m.Post("/hooks/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  326. m.Post("/hooks/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  327. m.Get("/hooks/:id", repo.WebHooksEdit)
  328. m.Post("/hooks/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  329. m.Post("/hooks/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  330. m.Route("/delete", "GET,POST", org.SettingsDelete)
  331. })
  332. m.Route("/invitations/new", "GET,POST", org.Invitation)
  333. }, middleware.OrgAssignment(true, true, true))
  334. }, reqSignIn)
  335. m.Group("/org", func() {
  336. m.Get("/:org", org.Home)
  337. }, ignSignIn, middleware.OrgAssignment(true))
  338. // Repository.
  339. m.Group("/repo", func() {
  340. m.Get("/create", repo.Create)
  341. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  342. m.Get("/migrate", repo.Migrate)
  343. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  344. m.Get("/fork", repo.Fork)
  345. m.Post("/fork", bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  346. }, reqSignIn)
  347. m.Group("/:username/:reponame", func() {
  348. m.Get("/settings", repo.Settings)
  349. m.Post("/settings", bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  350. m.Group("/settings", func() {
  351. m.Route("/collaboration", "GET,POST", repo.SettingsCollaboration)
  352. m.Get("/hooks", repo.Webhooks)
  353. m.Get("/hooks/new", repo.WebHooksNew)
  354. m.Post("/hooks/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  355. m.Post("/hooks/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  356. m.Get("/hooks/:id", repo.WebHooksEdit)
  357. m.Post("/hooks/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  358. m.Post("/hooks/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  359. m.Group("/hooks/git", func() {
  360. m.Get("", repo.GitHooks)
  361. m.Get("/:name", repo.GitHooksEdit)
  362. m.Post("/:name", repo.GitHooksEditPost)
  363. }, middleware.GitHookService())
  364. })
  365. }, reqSignIn, middleware.RepoAssignment(true), reqAdmin)
  366. m.Group("/:username/:reponame", func() {
  367. m.Get("/action/:action", repo.Action)
  368. m.Group("/issues", func() {
  369. m.Get("/new", repo.CreateIssue)
  370. m.Post("/new", bindIgnErr(auth.CreateIssueForm{}), repo.CreateIssuePost)
  371. m.Post("/:index", bindIgnErr(auth.CreateIssueForm{}), repo.UpdateIssue)
  372. m.Post("/:index/label", repo.UpdateIssueLabel)
  373. m.Post("/:index/milestone", repo.UpdateIssueMilestone)
  374. m.Post("/:index/assignee", repo.UpdateAssignee)
  375. m.Get("/:index/attachment/:id", repo.IssueGetAttachment)
  376. m.Post("/labels/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  377. m.Post("/labels/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  378. m.Post("/labels/delete", repo.DeleteLabel)
  379. m.Get("/milestones/new", repo.NewMilestone)
  380. m.Post("/milestones/new", bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  381. m.Get("/milestones/:index/edit", repo.UpdateMilestone)
  382. m.Post("/milestones/:index/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.UpdateMilestonePost)
  383. m.Get("/milestones/:index/:action", repo.UpdateMilestone)
  384. })
  385. m.Post("/comment/:action", repo.Comment)
  386. m.Group("/releases", func() {
  387. m.Get("/new", repo.NewRelease)
  388. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  389. m.Get("/edit/:tagname", repo.EditRelease)
  390. m.Post("/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  391. }, middleware.RepoRef())
  392. }, reqSignIn, middleware.RepoAssignment(true))
  393. m.Group("/:username/:reponame", func() {
  394. m.Get("/releases", middleware.RepoRef(), repo.Releases)
  395. m.Get("/issues", repo.Issues)
  396. m.Get("/issues/:index", repo.ViewIssue)
  397. m.Get("/issues/milestones", repo.Milestones)
  398. m.Get("/pulls", repo.Pulls)
  399. m.Get("/branches", repo.Branches)
  400. m.Get("/archive/*", repo.Download)
  401. m.Get("/issues2/", repo.Issues2)
  402. m.Get("/pulls2/", repo.PullRequest2)
  403. m.Get("/labels2/", repo.Labels2)
  404. m.Get("/milestone2/", repo.Milestones2)
  405. m.Group("", func() {
  406. m.Get("/src/*", repo.Home)
  407. m.Get("/raw/*", repo.SingleDownload)
  408. m.Get("/commits/*", repo.RefCommits)
  409. m.Get("/commit/*", repo.Diff)
  410. }, middleware.RepoRef())
  411. m.Get("/compare/:before([a-z0-9]+)...:after([a-z0-9]+)", repo.CompareDiff)
  412. }, ignSignIn, middleware.RepoAssignment(true))
  413. m.Group("/:username", func() {
  414. m.Get("/:reponame", ignSignIn, middleware.RepoAssignment(true, true), middleware.RepoRef(), repo.Home)
  415. m.Any("/:reponame/*", ignSignInAndCsrf, repo.Http)
  416. })
  417. // robots.txt
  418. m.Get("/robots.txt", func(ctx *middleware.Context) {
  419. if setting.HasRobotsTxt {
  420. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  421. } else {
  422. ctx.Error(404)
  423. }
  424. })
  425. // Not found handler.
  426. m.NotFound(routers.NotFound)
  427. // Flag for port number in case first time run conflict.
  428. if ctx.IsSet("port") {
  429. setting.AppUrl = strings.Replace(setting.AppUrl, setting.HttpPort, ctx.String("port"), 1)
  430. setting.HttpPort = ctx.String("port")
  431. }
  432. var err error
  433. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  434. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  435. switch setting.Protocol {
  436. case setting.HTTP:
  437. err = http.ListenAndServe(listenAddr, m)
  438. case setting.HTTPS:
  439. server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS10}, Handler: m}
  440. err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  441. case setting.FCGI:
  442. err = fcgi.Serve(nil, m)
  443. default:
  444. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  445. }
  446. if err != nil {
  447. log.Fatal(4, "Fail to start server: %v", err)
  448. }
  449. }