我想弄清楚是否有可能在编写 Web 应用程序时不必随处传递 http.ResponseWriter。我正在设置一个简单的 mvc web 框架,我发现自己必须通过各种函数传递 http.ResponseWriter,而它只用于让我们说最后一个函数。
路线包
// Struct containing http requests and variables
type UrlInfo struct {
Res http.ResponseWriter
Req *http.Request
Vars map[string]string
}
func HandleFunc(handlepath string, runfunc func(*UrlInfo)) {
// Set handler and setup struct
http.HandleFunc(getHandlePath(handlepath), func(w http.ResponseWriter, r *http.Request) {
url := new(UrlInfo)
url.Res = w
url.Req = r
url.Vars = parsePathVars(r.URL.Path, handlepath)
runfunc(url)
})
}
// Parse file and send to responsewriter
func View(w http.ResponseWriter, path string, data interface{}) {
// Go grab file from views folder
temp, err := template.ParseFiles(path+".html")
if err != nil {
// Couldnt find html file send error
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
temp.ExecuteTemplate(w, temp.Name(), data)
}
}
Controller 包
import (
"routes"
)
func init() {
// Build handlefunc
routes.HandleFunc("/home/", home)
}
func home(urlinfo *routes.UrlInfo) {
info := make(map[string]string)
info["Title"] = urlinfo.Vars["title"]
info["Body"] = "Body Info"
gi.View(urlinfo.Res, "pages/about", info)
}
我不想在 home 函数中传递任何东西,这样我就可以将它再次传递给 View 函数以吐出。能够将它放在一个地方并在需要时从中拉出会很好。对于以相同方式与路由包进行通信的多个包,这也很好。
欢迎任何想法、提示或技巧。谢谢。
最佳答案
有多种方法可以做到这一点。诀窍是从您正在通过的 ResponseWriter 中弄清楚您实际需要什么。听起来你只需要练习一点函数组合。
更改您的设计,以便 View 返回一个 io.Reader 和一个错误,然后您可以将其通过管道传输到 ResponseWriter。这是一个完全未经测试的示例:
func View(path string, data interface{}) (io.Reader, error) {
// Go grab file from views folder
temp, err := template.ParseFiles(path+".html")
if err != nil {
// Couldnt find html file send error
return nil, err
} else {
buf := bytes.Buffer()
temp.ExecuteTemplate(buf, temp.Name(), data)
return buf
}
}
func HandleFunc(handlepath string, runfunc func(*UrlInfo) (io.Reader, error)) {
// Set handler and setup struct
http.HandleFunc(getHandlePath(handlepath),
func(w http.ResponseWriter, r *http.Request) {
url := new(UrlInfo)
url.Res = w
url.Req = r
url.Vars = parsePathVars(r.URL.Path, handlepath)
rdr, err := runfunc(url)
io.Copy(w, rdr);
})
}
有了这个,唯一需要担心 http ResponseWriter 的就是你的 HandleFunc 函数。
关于golang 传递 http.ResponseWriter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12519660/
是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou
我没有找到太多关于如何执行此操作的信息,尽管有很多关于如何使用像这样的redirect_to将参数传递给重定向的建议:action=>'something',:controller=>'something'在我的应用程序中,我在路由文件中有以下内容match'profile'=>'User#show'我的表演Action是这样的defshow@user=User.find(params[:user])@title=@user.first_nameend重定向发生在同一个用户Controller中,就像这样defregister@title="Registration"@user=Use
我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur
我正在使用RubyonRails3.0.9,我想生成一个传递一些自定义参数的link_toURL。也就是说,有一个articles_path(www.my_web_site_name.com/articles)我想生成如下内容:link_to'Samplelinktitle',...#HereIshouldimplementthecode#=>'http://www.my_web_site_name.com/articles?param1=value1¶m2=value2&...我如何编写link_to语句“alàRubyonRailsWay”以实现该目的?如果我想通过传递一些
如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只
1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里
Rails中有没有一种方法可以提取与路由关联的HTTP动词?例如,给定这样的路线:将“users”匹配到:“users#show”,通过:[:get,:post]我能实现这样的目标吗?users_path.respond_to?(:get)(显然#respond_to不是正确的方法)我最接近的是通过执行以下操作,但它似乎并不令人满意。Rails.application.routes.routes.named_routes["users"].constraints[:request_method]#=>/^GET$/对于上下文,我有一个设置cookie然后执行redirect_to:ba
这是我的网络应用:classFront我是这样开始的(请不要建议使用Rack):Front.start!这是我的Puma配置对象,我不知道如何传递给它:require'puma/configuration'Puma::Configuration.new({log_requests:true,debug:true})说真的,怎么样? 最佳答案 配置与您运行的方式紧密相关puma服务器。运行的标准方式puma-pumaCLI命令。为了配置puma配置文件config/puma.rb或config/puma/.rb应该提供(参见examp
我正在使用Heroku(heroku.com)来部署我的Rails应用程序,并且正在构建一个iPhone客户端来与之交互。我的目的是将手机的唯一设备标识符作为HTTPheader传递给应用程序以进行身份验证。当我在本地测试时,我的header通过得很好,但在Heroku上它似乎去掉了我的自定义header。我用ruby脚本验证:url=URI.parse('http://#{myapp}.heroku.com/')#url=URI.parse('http://localhost:3000/')req=Net::HTTP::Post.new(url.path)#boguspara
我有一个电子邮件表格。但是我正在制作一个测试电子邮件表单,用户可以在其中添加一个唯一的电子邮件,并让电子邮件测试将其发送到该特定电子邮件。为了简单起见,我决定让测试电子邮件通过ajax执行,并将整个内容粘贴到另一个电子邮件表单中。我不知道如何将变量从我的HAML发送到我的Controllernew.html.haml-form_tagadmin_email_blast_pathdoSubject%br=text_field_tag'subject',:class=>"mass_email_subject"%brBody%br=text_area_tag'message','',:nam