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.

goget.go 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2021 The Gitea 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 web
  5. import (
  6. "net/http"
  7. "net/url"
  8. "path"
  9. "strings"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/context"
  12. "code.gitea.io/gitea/modules/setting"
  13. "code.gitea.io/gitea/modules/util"
  14. "github.com/unknwon/com"
  15. )
  16. func goGet(ctx *context.Context) {
  17. if ctx.Req.Method != "GET" || len(ctx.Req.URL.RawQuery) < 8 || ctx.FormString("go-get") != "1" {
  18. return
  19. }
  20. parts := strings.SplitN(ctx.Req.URL.EscapedPath(), "/", 4)
  21. if len(parts) < 3 {
  22. return
  23. }
  24. ownerName := parts[1]
  25. repoName := parts[2]
  26. // Quick responses appropriate go-get meta with status 200
  27. // regardless of if user have access to the repository,
  28. // or the repository does not exist at all.
  29. // This is particular a workaround for "go get" command which does not respect
  30. // .netrc file.
  31. trimmedRepoName := strings.TrimSuffix(repoName, ".git")
  32. if ownerName == "" || trimmedRepoName == "" {
  33. _, _ = ctx.Write([]byte(`<!doctype html>
  34. <html>
  35. <body>
  36. invalid import path
  37. </body>
  38. </html>
  39. `))
  40. ctx.Status(400)
  41. return
  42. }
  43. branchName := setting.Repository.DefaultBranch
  44. repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName)
  45. if err == nil && len(repo.DefaultBranch) > 0 {
  46. branchName = repo.DefaultBranch
  47. }
  48. prefix := setting.AppURL + path.Join(url.PathEscape(ownerName), url.PathEscape(repoName), "src", "branch", util.PathEscapeSegments(branchName))
  49. appURL, _ := url.Parse(setting.AppURL)
  50. insecure := ""
  51. if appURL.Scheme == string(setting.HTTP) {
  52. insecure = "--insecure "
  53. }
  54. ctx.Header().Set("Content-Type", "text/html")
  55. ctx.Status(http.StatusOK)
  56. _, _ = ctx.Write([]byte(com.Expand(`<!doctype html>
  57. <html>
  58. <head>
  59. <meta name="go-import" content="{GoGetImport} git {CloneLink}">
  60. <meta name="go-source" content="{GoGetImport} _ {GoDocDirectory} {GoDocFile}">
  61. </head>
  62. <body>
  63. go get {Insecure}{GoGetImport}
  64. </body>
  65. </html>
  66. `, map[string]string{
  67. "GoGetImport": context.ComposeGoGetImport(ownerName, trimmedRepoName),
  68. "CloneLink": models.ComposeHTTPSCloneURL(ownerName, repoName),
  69. "GoDocDirectory": prefix + "{/dir}",
  70. "GoDocFile": prefix + "{/dir}/{file}#L{line}",
  71. "Insecure": insecure,
  72. })))
  73. }