标签: gorilla

如何将参数传递给我的处理程序

我试图将我的数据库对象传递给我的处理程序,而不是拥有一个全局对象.但我不知道这是否可行,我正在使用Gorilla Mux包,我可以看到它需要一个封闭作为第二个参数.

// https://github.com/gorilla/mux/blob/master/mux.go#L174
// HandleFunc registers a new route with a matcher for the URL path.
// See Route.Path() and Route.HandlerFunc().
func (r *Router) HandleFunc(path string, f func(http.ResponseWriter,
    *http.Request)) *Route {
    return r.NewRoute().Path(path).HandlerFunc(f)
}
Run Code Online (Sandbox Code Playgroud)

然后定义了我可以使用的参数,理想情况下我希望有这样的第三个参数.

// In my main
router.HandleFunc("/users/{id}", showUserHandler).Methods("GET")

func showUserHandler(w http.ResponseWriter, r *http.Request, db *gorm.DB) {
    fmt.Fprintf(w, "We should fetch the user with id %s", vars["id"])
}
Run Code Online (Sandbox Code Playgroud)

有解决方法吗?或者我需要一个全局数据库对象?我是Go的新手,所以请详细解释一个可能的答案.

go gorilla

32
推荐指数
1
解决办法
2万
查看次数

Golang Gorilla mux与http.FileServer返回404

我看到的问题是我正在尝试使用http.FileServerGorilla mux Router.Handle功能.

这不起作用(图像返回404)..

myRouter := mux.NewRouter()
myRouter.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/"))))
Run Code Online (Sandbox Code Playgroud)

这工作(图像显示确定)..

http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/"))))
Run Code Online (Sandbox Code Playgroud)

简单的下面的web服务器程序,显示问题...

package main

import (
    "fmt"
    "net/http"
    "io"
    "log"
    "github.com/gorilla/mux"
)

const (
    HomeFolder = "/root/test/"
)

func HomeHandler(w http.ResponseWriter, req *http.Request) {
    io.WriteString(w, htmlContents)
}

func main() {

    myRouter := mux.NewRouter()
    myRouter.HandleFunc("/", HomeHandler)
    //
    // The next line, the image route handler results in 
    // the test.png image returning a 404.
    // myRouter.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/"))))
    //
    myRouter.Host("mydomain.com") …
Run Code Online (Sandbox Code Playgroud)

go gorilla

31
推荐指数
1
解决办法
1万
查看次数

Gorilla mux定制中间件

我正在使用gorilla mux进行管理路由.我缺少的是在每个请求之间集成中间件.

例如

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "log"
    "net/http"
    "strconv"
)

func HomeHandler(response http.ResponseWriter, request *http.Request) {

    fmt.Fprintf(response, "Hello home")
}

func main() {

    port := 3000
    portstring := strconv.Itoa(port)

    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)
    http.Handle("/", r)

    log.Print("Listening on port " + portstring + " ... ")
    err := http.ListenAndServe(":"+portstring, nil)
    if err != nil {
        log.Fatal("ListenAndServe error: ", err)
    }
}
Run Code Online (Sandbox Code Playgroud)

每个传入的请求都应该通过中间件.我怎样才能在这里整合中间件?

更新

我将它与大猩猩/会话结合使用,他们说:

重要说明:如果您不使用gorilla/mux,则需要使用context.ClearHandler包装处理程序,否则您将泄漏内存!一个简单的方法是在调用http.ListenAndServe时包装顶级多路复用器:

我该如何防止这种情况?

go gorilla

27
推荐指数
4
解决办法
2万
查看次数

对使用gorilla/mux URL参数的函数进行单元测试

这是我正在尝试做的事情:

main.go

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
)

func main() {
    mainRouter := mux.NewRouter().StrictSlash(true)
    mainRouter.HandleFunc("/test/{mystring}", GetRequest).Name("/test/{mystring}").Methods("GET")
    http.Handle("/", mainRouter)

    err := http.ListenAndServe(":8080", mainRouter)
    if err != nil {
        fmt.Println("Something is wrong : " + err.Error())
    }
}

func GetRequest(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    myString := vars["mystring"]

    w.WriteHeader(http.StatusOK)
    w.Header().Set("Content-Type", "text/plain")
    w.Write([]byte(myString))
}
Run Code Online (Sandbox Code Playgroud)

这将创建一个基于端口的基本http服务器,8080该服务器回显路径中给出的URL参数.因此,http://localhost:8080/test/abcd它将回写包含abcd在响应正文中的响应.

GetRequest()函数的单元测试在main_test.go中:

package main

import (
    "net/http"
    "net/http/httptest"
    "testing"

    "github.com/gorilla/context"
    "github.com/stretchr/testify/assert"
)

func TestGetRequest(t *testing.T) …
Run Code Online (Sandbox Code Playgroud)

unit-testing go gorilla testify

23
推荐指数
2
解决办法
1万
查看次数

使golang Gorilla CORS处理程序工作

我在这里设置相当简单,如下面的代码所述.但我无法CORS上班.我一直收到这个错误:

XMLHttpRequest无法加载http:// localhost:3000/signup.对预检请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头.因此不允许来源' http:// localhost:8000 '访问.响应具有HTTP状态代码403.

我相信我在这里缺少一些简单的东西.

这是我的代码:

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
    "myApp/src/controllers"
)

func main() {
    ac := new(controllers.AccountController)

    router := mux.NewRouter()
    router.HandleFunc("/signup", ac.SignUp).Methods("POST")
    router.HandleFunc("/signin", ac.SignIn).Methods("POST")

    log.Fatal(http.ListenAndServe(":3000", handlers.CORS()(router)))
}
Run Code Online (Sandbox Code Playgroud)

go cors gorilla servemux

21
推荐指数
5
解决办法
2万
查看次数

如何向Angular http请求添加授权标头?

这是我的第一篇文章.

我刚刚开始学习Go和Angular,我正在尝试将角度应用程序连接到go api.我已经写过这两篇文章而且很难找出问题的根源.我认为这是一个CORS问题,但如果我不在Angular http请求中包含代码标题行,它可以正常工作.此时我只是想添加标题.授权代码尚未实现.

这两个应用程序都在本地运行,端口5000上的Go应用程序和4200上的Angular

Angular http请求不起作用:

this.http.get<ProjectedBalance>(requestUrl, {headers: new HttpHeaders().set('Authorization', 'my-auth-token')})
    .subscribe(data => {
     this.projBalance = data.projBalance;
   }
Run Code Online (Sandbox Code Playgroud)

有效的Angular http请求:

this.http.get<ProjectedBalance>(requestUrl)
    .subscribe(data => {
     this.projBalance = data.projBalance;
   }
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

对预检请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头.因此不允许来源' http:// localhost:4200 '访问.响应具有HTTP状态代码403

我在我的代码中使用gorilla/mux和gorilla/handlers

router := mux.NewRouter()
router.HandleFunc("/home/{endDate}", GetProjBalance).Methods("GET", "OPTIONS")
headersOk := handlers.AllowedHeaders([]string{"X-Requested-With, Content-Type, Authorization"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
//start server on port
log.Fatal(http.ListenAndServe(":5000", handlers.CORS(originsOk, headersOk, methodsOk)(router)))
Run Code Online (Sandbox Code Playgroud)

来自Chrome Dev Tools的标题

Request URL:http://localhost:5000/home/2020-12-21
Request Method:OPTIONS
Status Code:403 Forbidden
Remote Address:[::1]:5000
Referrer Policy:no-referrer-when-downgrade

Response Headers …
Run Code Online (Sandbox Code Playgroud)

go gorilla angular

16
推荐指数
2
解决办法
4万
查看次数

无法使用go工具pprof与现有服务器

我有一个现有的http服务器,我想分析.我已经包含_ "net/http/pprof"了我的导入,并且我已经运行了http服务器:

router := createRouter()
server := &http.Server {
    Addr:           ":8080",
    Handler:        router,
    ReadTimeout:    15*time.Second,
    WriteTimeout:   15*time.Second,
//  MaxHeaderBytes: 4096,
}

log.Fatal(server.ListenAndServe())
Run Code Online (Sandbox Code Playgroud)

当我试图访问http:// localhost:8080/debug/pprof /我得到404 page not found.

这是我go tool pprof在本地机器上使用时得到的:

userver@userver:~/Desktop/gotest$ go tool pprof http://192.168.0.27:8080/
Use of uninitialized value $prefix in concatenation (.) or string at /usr/lib/go/pkg/tool/linux_amd64/pprof line 3019.
Read http://192.168.0.27:8080/pprof/symbol
Failed to get the number of symbols from http://192.168.0.27:8080/pprof/symbol

userver@userver:~/Desktop/gotest$ go tool pprof http://localhost:8080/debug/pprof/profile
Read http://localhost:8080/debug/pprof/symbol
Failed to get the …
Run Code Online (Sandbox Code Playgroud)

go pprof gorilla

13
推荐指数
3
解决办法
5208
查看次数

客户端未使用 websocket 协议:“连接”标头中未找到“升级”令牌

我正在使用 Gorilla Websocket 包来实现 websocket。

conn, err := upgrader.Upgrade(w, r, nil)

    if err != nil {
        // handle error
        fmt.Println(err)
    }
    defer conn.Close()
Run Code Online (Sandbox Code Playgroud)

我看到下面的错误

websocket:客户端未使用 websocket 协议:“连接”标头中未找到“升级”令牌

我打印在我的请求的标题上,我看到以下内容

conn, err := upgrader.Upgrade(w, r, nil)

    if err != nil {
        // handle error
        fmt.Println(err)
    }
    defer conn.Close()
Run Code Online (Sandbox Code Playgroud)

没有按预期升级 websocket 或连接升级

我相信我面临着与此完全相同的问题。

https http go websocket gorilla

13
推荐指数
2
解决办法
2万
查看次数

使用大猩猩会话时,不会保存golang中的会话变量

使用gorilla sessions Web工具包时,不会跨请求维护会话变量.当我启动服务器并输入localhost时:8100/page被定向到login.html,因为会话值不存在.登录后,我在商店中设置了会话变量,页面被重定向到home.html.但是当我打开一个新选项卡并输入localhost:8100时,应该使用已存储的会话变量将页面定向到home.html,但页面会被重定向到login.html.以下是代码.

    package main

import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
    "github.com/gocql/gocql"
    "github.com/gorilla/mux"
    "github.com/gorilla/sessions"
    "net/http"
    "time"
)

var store = sessions.NewCookieStore([]byte("something-very-secret"))

var router = mux.NewRouter()

func init() {

    store.Options = &sessions.Options{
        Domain:   "localhost",
        Path:     "/",
        MaxAge:   3600 * 1, // 1 hour
        HttpOnly: true,
    }
}
func main() {
    //session handling
    router.HandleFunc("/", SessionHandler)
    router.HandleFunc("/signIn", SignInHandler)
    router.HandleFunc("/signUp", SignUpHandler)
    router.HandleFunc("/logOut", LogOutHandler)
    http.Handle("/", router)
    http.ListenAndServe(":8100", nil)
}

//handler for signIn
func SignInHandler(res http.ResponseWriter, req *http.Request) {

    email := req.FormValue("email")
    password := req.FormValue("password")

    //Generate hash …
Run Code Online (Sandbox Code Playgroud)

session go gorilla

12
推荐指数
2
解决办法
9638
查看次数

在Gorilla Mux中嵌套子路由器

我一直在用gorilla/mux我的路由需求.但我注意到一个问题,当我嵌套多个Subrouters时,它不起作用.

这是一个例子:

func main() {
    r := mux.NewRouter().StrictSlash(true)
    api := r.Path("/api").Subrouter()
    u := api.Path("/user").Subrouter()
    u.Methods("GET").HandleFunc(UserHandler)
    http.ListenAndServe(":8080", r)
}
Run Code Online (Sandbox Code Playgroud)

我想使用这种方法,所以我可以委托将路由器填充到其他包中 user.Populate(api)

然而,这似乎不起作用.它只在我在链中使用单个Subrouter时才有效.

有任何想法吗?

routing go mux gorilla

12
推荐指数
1
解决办法
3909
查看次数

标签 统计

go ×10

gorilla ×10

angular ×1

cors ×1

http ×1

https ×1

mux ×1

pprof ×1

routing ×1

servemux ×1

session ×1

testify ×1

unit-testing ×1

websocket ×1