github.com/kotovmak/go-admin@v1.1.1/adm/template.go (about) 1 package main 2 3 import ( 4 "archive/zip" 5 "fmt" 6 "io" 7 "io/ioutil" 8 "net/http" 9 "os" 10 "path/filepath" 11 "strings" 12 13 "github.com/kotovmak/go-admin/modules/utils" 14 ) 15 16 func getThemeTemplate(moduleName, themeName string) { 17 18 downloadTo("http://file.go-admin.cn/go_admin/template/template.zip", "tmp.zip") 19 20 checkError(unzipDir("tmp.zip", ".")) 21 22 checkError(os.Rename("./QiAtztVk83CwCh", "./"+themeName)) 23 24 replaceContents("./"+themeName, moduleName, themeName) 25 26 checkError(os.Rename("./"+themeName+"/template.go", "./"+themeName+"/"+themeName+".go")) 27 28 fmt.Println() 29 fmt.Println("generate theme template success!!🍺🍺") 30 fmt.Println() 31 } 32 33 func downloadTo(url, output string) { 34 defer func() { 35 _ = os.Remove(output) 36 }() 37 38 req, err := http.NewRequest("GET", url, nil) 39 40 checkError(err) 41 42 res, err := http.DefaultClient.Do(req) 43 44 checkError(err) 45 46 defer func() { 47 _ = res.Body.Close() 48 }() 49 50 file, err := os.Create(output) 51 52 checkError(err) 53 54 _, err = io.Copy(file, res.Body) 55 56 checkError(err) 57 } 58 59 func unzipDir(src, dest string) error { 60 r, err := zip.OpenReader(src) 61 if err != nil { 62 return err 63 } 64 defer func() { 65 if err := r.Close(); err != nil { 66 panic(err) 67 } 68 }() 69 70 checkError(os.MkdirAll(dest, 0750)) 71 72 // Closure to address file descriptors issue with all the deferred .Close() methods 73 extractAndWriteFile := func(f *zip.File) error { 74 rc, err := f.Open() 75 if err != nil { 76 return err 77 } 78 defer func() { 79 if err := rc.Close(); err != nil { 80 panic(err) 81 } 82 }() 83 84 path := filepath.Join(dest, f.Name) 85 86 if f.FileInfo().IsDir() { 87 checkError(os.MkdirAll(path, f.Mode())) 88 } else { 89 checkError(os.MkdirAll(filepath.Dir(path), f.Mode())) 90 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) 91 if err != nil { 92 return err 93 } 94 defer func() { 95 if err := f.Close(); err != nil { 96 panic(err) 97 } 98 }() 99 100 _, err = io.Copy(f, rc) 101 if err != nil { 102 return err 103 } 104 } 105 return nil 106 } 107 108 for _, f := range r.File { 109 err := extractAndWriteFile(f) 110 if err != nil { 111 return err 112 } 113 } 114 115 return nil 116 } 117 118 func replaceContents(fileDir, moduleName, themeName string) { 119 files, err := ioutil.ReadDir(fileDir) 120 checkError(err) 121 for _, file := range files { 122 path := fileDir + "/" + file.Name() 123 if !file.IsDir() { 124 buf, err := ioutil.ReadFile(path) 125 checkError(err) 126 content := string(buf) 127 128 newContent := utils.ReplaceAll(content, "github.com/GoAdminGroup/themes/adminlte", moduleName, 129 "adminlte", themeName, "Adminlte", strings.Title(themeName)) 130 131 checkError(ioutil.WriteFile(path, []byte(newContent), 0)) 132 } 133 } 134 }