go_get.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2022 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 and LICENSE.gogs file.
  4. // Copyright 2025 Huan-Gogs Authors. All rights reserved.
  5. // Use of this source code is governed by a MIT-style
  6. // license that can be found in the LICENSE file.
  7. package context
  8. import (
  9. "net/http"
  10. "path"
  11. "strings"
  12. "github.com/unknwon/com"
  13. "gopkg.in/macaron.v1"
  14. "github.com/SongZihuan/huan-gogs/internal/conf"
  15. "github.com/SongZihuan/huan-gogs/internal/database"
  16. "github.com/SongZihuan/huan-gogs/internal/repoutil"
  17. )
  18. // ServeGoGet does quick responses for appropriate go-get meta with status OK
  19. // regardless of whether the user has access to the repository, or the repository
  20. // does exist at all. This is particular a workaround for "go get" command which
  21. // does not respect .netrc file.
  22. func ServeGoGet() macaron.Handler {
  23. return func(c *macaron.Context) {
  24. if c.Query("go-get") != "1" {
  25. return
  26. }
  27. ownerName := c.Params(":username")
  28. repoName := c.Params(":reponame")
  29. branchName := "master"
  30. owner, err := database.Handle.Users().GetByUsername(c.Req.Context(), ownerName)
  31. if err == nil {
  32. repo, err := database.Handle.Repositories().GetByName(c.Req.Context(), owner.ID, repoName)
  33. if err == nil && repo.DefaultBranch != "" {
  34. branchName = repo.DefaultBranch
  35. }
  36. }
  37. prefix := conf.Server.ExternalURL + path.Join(ownerName, repoName, "src", branchName)
  38. insecureFlag := ""
  39. if !strings.HasPrefix(conf.Server.ExternalURL, "https://") {
  40. insecureFlag = "--insecure "
  41. }
  42. c.PlainText(http.StatusOK, []byte(com.Expand(`<!doctype html>
  43. <html>
  44. <head>
  45. <meta name="go-import" content="{GoGetImport} git {CloneLink}">
  46. <meta name="go-source" content="{GoGetImport} _ {GoDocDirectory} {GoDocFile}">
  47. </head>
  48. <body>
  49. go get {InsecureFlag}{GoGetImport}
  50. </body>
  51. </html>
  52. `,
  53. map[string]string{
  54. "GoGetImport": path.Join(conf.Server.URL.Host, conf.Server.Subpath, ownerName, repoName),
  55. "CloneLink": repoutil.HTTPSCloneURL(ownerName, repoName),
  56. "GoDocDirectory": prefix + "{/dir}",
  57. "GoDocFile": prefix + "{/dir}/{file}#L{line}",
  58. "InsecureFlag": insecureFlag,
  59. },
  60. )))
  61. }
  62. }