Ejemplo n.º 1
0
func MustAddFileToHttpPathToServeMux(mux *http.ServeMux, httpPath string, localFilePath string) {
	localFilePath, err := kmgFile.Realpath(localFilePath)
	//_, err := os.Stat(localFilePath)
	if err != nil {
		panic(err)
	}
	if !strings.HasPrefix(httpPath, "/") {
		httpPath = "/" + httpPath
	}
	if !strings.HasSuffix(httpPath, "/") {
		httpPath = httpPath + "/"
	}
	mux.HandleFunc(httpPath, CompressHandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		urlPath := req.URL.Path
		relPath := strings.TrimPrefix(urlPath, httpPath)
		filePath := filepath.Join(localFilePath, relPath)
		fi, err := os.Stat(filePath)
		if err != nil {
			http.NotFound(w, req)
			return
		}
		if fi.IsDir() {
			http.NotFound(w, req)
			return
		}
		http.ServeFile(w, req, filePath)
	}))
	/*
		if fi.IsDir() {
			if !strings.HasSuffix(httpPath, "/") {
				httpPath += "/"
			}
			mux.Handle(httpPath, http.StripPrefix(httpPath, http.FileServer(http.Dir(localFilePath))))
		} else {
			mux.HandleFunc(httpPath, func(w http.ResponseWriter, req *http.Request) {
				http.ServeFile(w, req, localFilePath)
			})
		}
	*/
	return
}
Ejemplo n.º 2
0
func (command *GoAllImport) Execute(context *console.Context) (err error) {
	kmgc, err := kmgConfig.LoadEnvFromWd()
	if err != nil {
		return
	}
	command.gopath = kmgc.GOPATH[0]
	root := command.dir
	exist, err := kmgFile.FileExist(root)
	if err != nil {
		return
	}
	if !exist {
		return fmt.Errorf("[GoAllImport] dir path[%s] not exist", root)
	}
	c := &build.Context{
		GOPATH:   kmgc.GOPATHToString(),
		Compiler: build.Default.Compiler,
	}
	root, err = kmgFile.Realpath(root)
	if err != nil {
		return
	}
	moduleList := []string{}
	err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			return nil
		}
		if kmgFile.IsDotFile(path) {
			return filepath.SkipDir
		}
		pkg, err := c.ImportDir(path, build.ImportMode(0))
		if err != nil {
			//忽略异常文件夹,(不是golang的目录之类的)
			return nil
		}
		if pkg.IsCommand() {
			return nil
		}

		pkgFullName, err := filepath.Rel(command.gopath, path)
		if err != nil {
			return err
		}
		moduleList = append(moduleList, strings.TrimPrefix(filepath.ToSlash(pkgFullName), "src/"))
		return nil
	})
	if err != nil {
		return
	}
	tpl := template.Must(template.New("").Parse(`package {{.PackageName}}
import(
{{range .ModuleList}}	_ "{{.}}"
{{end}}
)
`))
	buf := &bytes.Buffer{}
	tpl.Execute(buf, struct {
		PackageName string
		ModuleList  []string
	}{
		PackageName: command.packageName,
		ModuleList:  moduleList,
	})
	fmt.Println(string(buf.Bytes()))
	return
}