go_get.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package context
  2. import (
  3. "net/http"
  4. "path"
  5. "strings"
  6. "github.com/flamego/flamego"
  7. "github.com/unknwon/com"
  8. "gogs.io/gogs/internal/conf"
  9. "gogs.io/gogs/internal/database"
  10. "gogs.io/gogs/internal/repoutil"
  11. )
  12. // ServeGoGet does quick responses for appropriate go-get meta with status OK
  13. // regardless of whether the user has access to the repository, or the repository
  14. // does exist at all. This is particular a workaround for "go get" command which
  15. // does not respect .netrc file.
  16. func ServeGoGet() flamego.Handler {
  17. return func(fctx flamego.Context, w http.ResponseWriter, req *http.Request) {
  18. if fctx.Query("go-get") != "1" {
  19. return
  20. }
  21. ownerName := fctx.Param("username")
  22. repoName := fctx.Param("reponame")
  23. branchName := "master"
  24. owner, err := database.Handle.Users().GetByUsername(req.Context(), ownerName)
  25. if err == nil {
  26. repo, err := database.Handle.Repositories().GetByName(req.Context(), owner.ID, repoName)
  27. if err == nil && repo.DefaultBranch != "" {
  28. branchName = repo.DefaultBranch
  29. }
  30. }
  31. prefix := conf.Server.ExternalURL + path.Join(ownerName, repoName, "src", branchName)
  32. insecureFlag := ""
  33. if !strings.HasPrefix(conf.Server.ExternalURL, "https://") {
  34. insecureFlag = "--insecure "
  35. }
  36. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  37. w.WriteHeader(http.StatusOK)
  38. w.Write([]byte(com.Expand(`<!doctype html>
  39. <html>
  40. <head>
  41. <meta name="go-import" content="{GoGetImport} git {CloneLink}">
  42. <meta name="go-source" content="{GoGetImport} _ {GoDocDirectory} {GoDocFile}">
  43. </head>
  44. <body>
  45. go get {InsecureFlag}{GoGetImport}
  46. </body>
  47. </html>
  48. `,
  49. map[string]string{
  50. "GoGetImport": path.Join(conf.Server.URL.Host, conf.Server.Subpath, ownerName, repoName),
  51. "CloneLink": repoutil.HTTPSCloneURL(ownerName, repoName),
  52. "GoDocDirectory": prefix + "{/dir}",
  53. "GoDocFile": prefix + "{/dir}/{file}#L{line}",
  54. "InsecureFlag": insecureFlag,
  55. },
  56. )))
  57. }
  58. }