template.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package docker
  2. import (
  3. "github.com/urfave/cli"
  4. "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
  5. )
  6. const (
  7. category = "docker"
  8. dockerTemplateFile = "docker.tpl"
  9. dockerTemplate = `FROM golang:{{.Version}}alpine AS builder
  10. LABEL stage=gobuilder
  11. ENV CGO_ENABLED 0
  12. ENV GOOS linux
  13. {{if .Chinese}}ENV GOPROXY https://goproxy.cn,direct
  14. {{end}}{{if .HasTimezone}}
  15. RUN apk update --no-cache && apk add --no-cache tzdata
  16. {{end}}
  17. WORKDIR /build
  18. ADD go.mod .
  19. ADD go.sum .
  20. RUN go mod download
  21. COPY . .
  22. {{if .Argument}}COPY {{.GoRelPath}}/etc /app/etc
  23. {{end}}RUN go build -ldflags="-s -w" -o /app/{{.ExeFile}} {{.GoRelPath}}/{{.GoFile}}
  24. FROM {{if .Scratch}}scratch{{else}}alpine{{end}}
  25. {{if .Scratch}}COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt{{else}}RUN apk update --no-cache && apk add --no-cache ca-certificates{{end}}
  26. {{if .HasTimezone}}COPY --from=builder /usr/share/zoneinfo/{{.Timezone}} /usr/share/zoneinfo/{{.Timezone}}
  27. ENV TZ {{.Timezone}}
  28. {{end}}
  29. WORKDIR /app
  30. COPY --from=builder /app/{{.ExeFile}} /app/{{.ExeFile}}{{if .Argument}}
  31. COPY --from=builder /app/etc /app/etc{{end}}
  32. {{if .HasPort}}
  33. EXPOSE {{.Port}}
  34. {{end}}
  35. CMD ["./{{.ExeFile}}"{{.Argument}}]
  36. `
  37. )
  38. // Clean deletes all templates files
  39. func Clean() error {
  40. return pathx.Clean(category)
  41. }
  42. // GenTemplates creates docker template files
  43. func GenTemplates(_ *cli.Context) error {
  44. return initTemplate()
  45. }
  46. // Category returns the const string of docker category
  47. func Category() string {
  48. return category
  49. }
  50. // RevertTemplate recovers the deleted template files
  51. func RevertTemplate(name string) error {
  52. return pathx.CreateTemplate(category, name, dockerTemplate)
  53. }
  54. // Update deletes and creates new template files
  55. func Update() error {
  56. err := Clean()
  57. if err != nil {
  58. return err
  59. }
  60. return initTemplate()
  61. }
  62. func initTemplate() error {
  63. return pathx.InitTemplates(category, map[string]string{
  64. dockerTemplateFile: dockerTemplate,
  65. })
  66. }