如何处理这些路由:/example/log 和 /example/:id/log?

huangapple go评论91阅读模式
英文:

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!

huangapple
  • 本文由 发表于 2016年10月31日 21:48:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/40343515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定