Go web应用程序的目录结构 [英] Directory structure for Go web app

查看:212
本文介绍了Go web应用程序的目录结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循Go网站上的编写Web应用程序教程,我是开始写我自己的网络应用程序。我也读过如何编写Go Code 的开头,并试图将我的代码与相同的工作空间结构。



我正在编写一个名为mygosite的简单Web应用程序,通过渲染单个模板来处理所有请求。运行去安装github.com/wesleym/mygosite 后,我的目录结构如下所示:

 
+ -src
| + -github.com
| + -wesleym
| + -mygosite
| + -mygosite.go
| + -templates
| + - index.html
| + - .git
+ -bin
+ -mygosite

在我的代码中,我指的是模板路径 templates / index.html 。当我运行 bin / mygosite 时,应用程序找不到我的模板,因为它位于源代码树中。由于模板对我的应用程序很重要,我不想将它们移到我的mygosite git存储库之外。



我的目录布局是否合理?去做?我应该在我的代码中将模板路径更改为 src / github.com / wesleym / mygosite / templates / index.html ?什么样的静态资产,如CSS和JavaScript - 应该在什么时候引入它们?

tl; dr:我在哪里放置模板和静态Go的web应用程序项目中的文件?

解决方案


Go Web应用程序项目中的静态文件?


是错误的问题。如果你问我的可执行文件如何找到它的资源?你几乎在解决方案:你的可执行文件应该从一个(或几个)可配置的位置读取其资源(并且提供合理的默认值总是很好)。当前工作目录中的命令行标志,环境变量和配置文件对于这些任务很常见。 (当然,如果你只有少量的小资源:按照VonC的建议将它们打包到你的可执行文件中;一旦你开始包括像图片或视频这样的大资产,这种方案就会崩溃。)


I've followed the Writing Web Applications tutorial on the Go website and I'm starting to write my own web app. I've also read the beginning of How to Write Go Code and am trying to organise my code with the same workspace structure.

I'm writing a simple web app named mygosite that handles all requests by rendering a single template. After running go install github.com/wesleym/mygosite, my directory structure now looks like this:

go
+-src
| +-github.com
|   +-wesleym
|     +-mygosite
|       +-mygosite.go
|       +-templates
|         +- index.html
|       +-.git
+-bin
  +-mygosite

In my code, I'm referring to the template with path templates/index.html. When I run bin/mygosite, the app can't find my template because it's in the source tree. Since the templates are important to my app, I don't want to move them outside of my mygosite git repository.

Is my directory layout reasonable given what I'm trying to do? Should I change the path to my template in my code to be src/github.com/wesleym/mygosite/templates/index.html? What about static assets like CSS and JavaScript - where should those go when the time comes to introduce them?

tl;dr: Where do I put templates and static files in a Go web application project?

解决方案

Where do I put templates and static files in a Go web application project?

is the "wrong" question. If you ask "How will my executable find its resources?" you are almost at the solution: Your executable should read its resources from a (or several) locations which are configurable (and it is always nice to provide sensible defaults). Command line flags, environment variables and config files in the current working directory are common for such tasks. (Of course, if you just have a handful of small resources: Pack them into your executable as VonC recommended; this scheme just breaks down once you start including large assets like images or video.)

这篇关于Go web应用程序的目录结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆