英文:
Go HTTP handler - handling more than two form actions
问题
我有一个webapp,其中有以下代码:
func handler (w res, r req) {
if req.Method == POST {
// 创建带有提交按钮2的html表单2
return ;
}
// 创建带有提交按钮1的html表单1
return
}
func main() {
handle("/", handler)
}
现在,根目录/已经注册了handler函数。在第一个请求(GET)中,我创建一个表单并将其发送给用户。如果用户提交了这个表单,我会在“POST”方法下处理它。现在,在post方法的处理程序中,我创建了一个不同的表单,现在我想要一种方法来根据用户在这个表单2中输入的内容执行一些操作,当他/她提交表单2时。
在Go中,处理表单2的提交有什么标准方法?我之前做过一些asp编程,我们使用表单操作将其提交到不同的asp文件。如何根据解析表单2的提交请求执行一些操作?
英文:
I have a webapp where I have code like:
func handler (w res, r req) {
if req.Method == POST {
// create html form 2 with a submit button2
return ;
}
// create html form 1 with a submit button1
return
}
func main() {
handle("/", handler)
}
Now, the root / is registered with the handler func. In the first request (GET), I create a form and send it to the user. If the user submits this form, I handle it under the "POST" method. Now, I create a different form in the post method handler, and now I want a way to do some operations based on what the user typed in this form2, when
What is the standard way with go to handle the form2 form submission ? I have done some asp programming earlier and we use form action to submit to a different asp file. How can I do some actions based on parsing the form2 submission request ?
答案1
得分: 4
如果我理解你的问题正确的话,你想要一种根据请求的方法而不仅仅是路径来路由相同URL到不同处理程序的方法?如果是这样的话...
以Python + Django为例,你目前的做法是相当标准的:
def my_django_view(request):
if request.method == "POST":
try_to_process_posted_data()
elif request.method == "GET":
show_a_form_to_user()
如果你想要更高级的功能,比如基于路径和请求方法(GET、POST、DELETE等)进行URL路由,那么你可能会对Gorilla.mux这样的东西感兴趣。
它提供了一些友好的URL路由方法:
func main() {
router := mux.NewRouter()
router.HandleFunc("/", YourGETHandlerFunc).Methods("GET")
router.HandleFunc("/", YourPOSTHandlerFunc).Methods("POST")
http.Handle("/", router)
}
如果你正在寻找更多的Web开发资源...
- Mango: http://paulbellamy.com/2011/05/introducing-mango/
- Web.go: http://www.getwebgo.com/tutorial
- Twister: https://github.com/garyburd/twister/blob/master/examples/hello/main.go
英文:
If I'm understanding you correctly, you want a way of routing the same URL to different handlers based on the request method rather than just the path? If that's the case...
For comparison, using Python + Django, the way you're doing this is pretty standard:
def my_django_view(request):
if request.method == "POST":
try_to_process_posted_data()
elif request.method == "GET":
show_a_form_to_user()
If you are trying to do fancier things like URL routing based on path and request method (GET, POST, DELETE, ...), then you might be interested in something like Gorilla.mux
It provides some friendly URL routing methods:
func main() {
router := mux.NewRouter()
router.HandleFunc("/", YourGETHandlerFunc).Methods("GET")
router.HandleFunc("/", YourPOSTHandlerFunc).Methods("POST")
http.Handle("/", router)
}
If you're looking for more resources for web development...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论