英文:
How to handle these routes: /example/log and /example/:id/log?
问题
我尝试了类似这样的代码:
router.GET("/example/log", logAllHandler)
router.GET("/example/:id/log", logHandler)
但是 Gin 不允许这样做,并在启动时出现错误。
一个想法是编写一个中间件来处理这种情况,但是...
英文:
I tried something like this:
router.GET("/example/log", logAllHandler)
router.GET("/example/:id/log", logHandler)
But Gin does not allow this and panics upon start.
An idea is write a middleware to handle this case, but ...
答案1
得分: 8
我已经成功完成了。希望这对你有所帮助:
package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"log"
"net/http"
)
func logAll(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
if ps.ByName("id") == "log" {
fmt.Fprintf(w, "Log All")
}
}
func logSpecific(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "Log Specific, %s!\n", ps.ByName("id"))
}
func main() {
router := httprouter.New()
router.GET("/example/:id", logAll)
router.GET("/example/:id/log", logSpecific)
log.Fatal(http.ListenAndServe(":8081", router))
}
运行示例:
$ curl http://127.0.0.1:8081/example/log
Log All
$ curl http://127.0.0.1:8081/example/abc/log
Log Specific, abc!
英文:
I have success to do it. Hope that it will help you:
package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"log"
"net/http"
)
func logAll(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
if ps.ByName("id") == "log" {
fmt.Fprintf(w, "Log All")
}
}
func logSpecific(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "Log Specific, %s!\n", ps.ByName("id"))
}
func main() {
router := httprouter.New()
router.GET("/example/:id", logAll)
router.GET("/example/:id/log", logSpecific)
log.Fatal(http.ListenAndServe(":8081", router))
}
Example of running
$ curl http://127.0.0.1:8081/example/log
Log All
$ curl http://127.0.0.1:8081/example/abc/log
Log Specific, abc!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论