template.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. {{if .Chinese}}ENV GOPROXY https://goproxy.cn,direct
  13. {{end}}{{if .HasTimezone}}
  14. RUN apk update --no-cache && apk add --no-cache tzdata
  15. {{end}}
  16. WORKDIR /build
  17. ADD go.mod .
  18. ADD go.sum .
  19. RUN go mod download
  20. COPY . .
  21. {{if .Argument}}COPY {{.GoRelPath}}/etc /app/etc
  22. {{end}}RUN go build -ldflags="-s -w" -o /app/{{.ExeFile}} {{.GoRelPath}}/{{.GoFile}}
  23. FROM {{.BaseImage}}
  24. COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
  25. {{if .HasTimezone}}COPY --from=builder /usr/share/zoneinfo/{{.Timezone}} /usr/share/zoneinfo/{{.Timezone}}
  26. ENV TZ {{.Timezone}}
  27. {{end}}
  28. WORKDIR /app
  29. COPY --from=builder /app/{{.ExeFile}} /app/{{.ExeFile}}{{if .Argument}}
  30. COPY --from=builder /app/etc /app/etc{{end}}
  31. {{if .HasPort}}
  32. EXPOSE {{.Port}}
  33. {{end}}
  34. CMD ["./{{.ExeFile}}"{{.Argument}}]
  35. `
  36. )
  37. // Clean deletes all templates files
  38. func Clean() error {
  39. return pathx.Clean(category)
  40. }
  41. // GenTemplates creates docker template files
  42. func GenTemplates(_ *cli.Context) error {
  43. return initTemplate()
  44. }
  45. // Category returns the const string of docker category
  46. func Category() string {
  47. return category
  48. }
  49. // RevertTemplate recovers the deleted template files
  50. func RevertTemplate(name string) error {
  51. return pathx.CreateTemplate(category, name, dockerTemplate)
  52. }
  53. // Update deletes and creates new template files
  54. func Update() error {
  55. err := Clean()
  56. if err != nil {
  57. return err
  58. }
  59. return initTemplate()
  60. }
  61. func initTemplate() error {
  62. return pathx.InitTemplates(category, map[string]string{
  63. dockerTemplateFile: dockerTemplate,
  64. })
  65. }