我试图在给定的例子中将字符串传递给处理程序。
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
这是我尝试的但它会抛出一个错误,因为它需要常规的参数数量:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request, s *string) {
fmt.Fprintf(w, "Hi there, I love %s!", *s)
}
func main() {
files := "bar"
http.HandleFunc("/", handler(&files))
http.ListenAndServe(":8080", nil)
}
答案 0 :(得分:2)
我对你要做的事情有点不清楚,但根据你所说的,为什么不试着像这样封装你想要传递的数据:
package main
import (
"fmt"
"net/http"
)
type FilesHandler struct {
Files string
}
func (fh *FilesHandler) handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", fh.Files)
}
func main() {
myFilesHandler := &FilesHandler{Files: "bar"}
http.HandleFunc("/", myFilesHandler.handler)
http.ListenAndServe(":8080", nil)
}
这样可以更精细地控制您为处理程序提供的内容。
答案 1 :(得分:1)
这里有很多选项,你可以:
这取决于什么是真的 - 它是一个常量,它是基于某个状态,是否属于一个单独的包?
答案 2 :(得分:0)
其中一种方法是将数据存储在全局变量中:
package main
import (
"fmt"
"net/http"
)
var replies map[string]string
func handler1(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
question := r.FormValue("question")
var answer string
var ok bool
if answer, ok = replies[question]; !ok {
answer = "I have no answer for this"
}
fmt.Fprintf(w, "Hi there, I love %s! My answer is: %s", question, answer)
}
func main() {
//files := "bar"
replies = map[string]string{
"UK": "London",
"FR": "Paris",
}
http.HandleFunc("/", handler1)
http.ListenAndServe(":8080", nil)
}
为简洁起见,我已将文件注释掉并将数据按原样放入地图中。您可以阅读该文件并将其放在那里。
使用CURL:
$ curl -X POST 127.0.0.1:8080/ -d "question=FR"
Hi there, I love FR! My answer is: Paris
$ curl -X POST 127.0.0.1:8080/ -d "question=US"
Hi there, I love US! My answer is: I have no answer for this