我正在制作一个api,并使用swaggo/swag来构建一个swagger接口。以前,我使用的是net/http包,一切都很好。
我切换到了julienschmidt/httprouter,但我没有设法使swagger界面再次工作。这是我的密码
package main
import (
"fmt"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
httpSwagger "github.com/swaggo/http-swagger"
)
func main() {
router := httprouter.New()
router.ServeFiles("/api/doc/static/*filepath", http.Dir("api/swagger/static"))
router.HandlerFunc(http.MethodGet, "/api/doc/index.html", swaggerHandler)
// router.HandlerFunc(http.MethodGet, "/api/doc", swaggerHandler)
fmt.Println("Server on port 8080")
log.Fatal(http.ListenAndServe(":8080", router))
}
func swaggerHandler(w http.ResponseWriter, r *http.Request) {
swaggerFileUrl := "http://localhost:8080/api/doc/static/swagger.json"
handler := httpSwagger.Handler(httpSwagger.URL(swaggerFileUrl))
handler.ServeHTTP(w, r)
}我检查了swaggerFileUrl变量是否正确,并且能够使用这个url访问json文件。界面是一个完整的空白页面,标题为"Swagger“。因为标题被替换了,我假设发生了一些事情,但是我不知道这个问题是来自httpSwagger还是httprouter。
编辑:导致问题是因为加载接口的javascript文件不存在。参见此github问题
发布于 2021-05-17 10:16:53
你可以这样做:
routes := httprouter.New()
routes.GET("/doc/:any", swaggerHandler)
func swaggerHandler(res http.ResponseWriter, req *http.Request, p httprouter.Params) {
httpSwagger.WrapHandler(res, req)
}不要忘记导入文档文件
import (
_ "example.project/docs"
)https://stackoverflow.com/questions/67356825
复制相似问题