我有一个服务器代码和一个用于搜索字符串的 html 表单。服务器处理程序获取字符串并搜索相同的字符串。但我在这里面临两个问题。
1.即使我将其设为POST,方法名称也始终是GET。
2.我无法在服务器端接收表单值
服务器代码在这里,
package main
import (
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"net"
"net/http"
"regexp"
//"bytes"
)
var (
addr = flag.Bool("addr", false, "find open address and print to final-port.txt")
)
type Page struct {
Title string
Body []byte
}
type UserInfo struct {
Title string
UserId string
UserName string
}
func (p *Page) save() error {
filename := "projects/" + p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
func loadPage(title string) (*Page, error) {
filename := "projects/" + title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return &Page{Title: title, Body: body}, nil
}
//Home page handler
//Hard coding the user name
func homeHandler(w http.ResponseWriter, r *http.Request, title string) {
p := &UserInfo{Title: "Project Tube",UserId: "dxa132330", UserName: "Dinesh Appavoo"}
renderTemplate(w, "home", p)
}
//Search project handler
func searchHandler(w http.ResponseWriter, r *http.Request, title string) {
fmt.Println("method:", r.Method) //get request method
r.ParseForm()
if r.Method == "GET" {
form_data := r.FormValue("form_data")
fmt.Println("Form Data : ",form_data)
fmt.Println("Form Data 1: ",r.Form)
for _,val := range r.FormValue("search_string") {
fmt.Println("Search string: ", val)
}
} else {
r.ParseForm()
fmt.Println("Search string:", r.FormValue("search_string"))
}
p := &UserInfo{Title: "Project Tube",UserId: "dxa132330", UserName: "Dinesh Appavoo"}
renderTemplate(w, "searchproject", p)
}
var templates = template.Must(template.ParseFiles("home.html", "editproject.html", "viewproject.html", "searchproject.html", "header.html", "footer.html"))
func renderTemplate(w http.ResponseWriter, tmpl string, p interface{}) {
//If you use variables other than the struct u r passing as p, then "multiple response.WriteHeader calls" error may occur. Make sure you pass
//all variables in the struct even they are in the header.html embedded
if err := templates.ExecuteTemplate(w, tmpl+".html", p); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
//URL validation
var validPath = regexp.MustCompile("^/(home|editproject|saveproject|viewproject|searchproject)/(|[a-zA-Z0-9]+)$")
func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
m := validPath.FindStringSubmatch(r.URL.Path)
if m == nil {
http.NotFound(w, r)
return
}
fn(w, r, m[2])
}
}
func main() {
flag.Parse()
TestConn()
http.HandleFunc("/home/", makeHandler(homeHandler))
http.HandleFunc("/searchproject/", makeHandler(searchHandler))
http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("resources"))))
if *addr {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
log.Fatal(err)
}
err = ioutil.WriteFile("final-port.txt", []byte(l.Addr().String()), 0644)
if err != nil {
log.Fatal(err)
}
s := &http.Server{}
s.Serve(l)
return
}
http.ListenAndServe(":8080", nil)
}
我在 searchHandler 函数中遇到了问题。我的 html 代码在这里
{{ template "header.html" . }}
<br><br>
<div class="container">
<form action="/searchproject" method="GET">
<div class="form-group">
<input type="text" class="form-control" name="search_string">
</div>
<button type="submit" class="btn btn-success">Search</button>
</form>
</div>
服务器控制台日志如下,
method: GET
Form Data :
Form Data 1: map[]
谁能帮我解决这个问题?谢谢。
最佳答案
那是你遇到的一个微妙问题。
非常巧妙地,您在 searchproject url 上有一个尾部斜杠,导致从服务器发出 301 重定向。
表单执行 POST(或 GET)到/searchproject 和服务器,非常友善地说浏览器应该转到/searchproject/(添加尾部斜杠!),浏览器执行 GET 并丢失表单数据在此过程中。
我认为这个例子可以满足您的需求:
package main
import (
"fmt"
"net/http"
)
func searchHandler(w http.ResponseWriter, r *http.Request) {
fmt.Printf("%+v\n", r)
fmt.Fprintln(w, "OK")
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, SEARCH_PAGE)
}
func main() {
http.HandleFunc("/", homeHandler)
http.HandleFunc("/searchproject", searchHandler)
http.ListenAndServe(":8080", nil)
}
const SEARCH_PAGE = `
<html>
<body>
<form action="searchproject" method="POST">
<input type="text" name="search_string">
<input type="submit" value="Search">
</form>
</body>
</html>
`
关于forms - Golang html GET 表单方法值未被填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29004147/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib
我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢