golang 去我的博客文章中间件样本。 http://justinas.org/writing-http-middleware-in-go/

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang 去我的博客文章中间件样本。 http://justinas.org/writing-http-middleware-in-go/相关的知识,希望对你有一定的参考价值。

package main

import (
	"net/http"
	"net/http/httptest"
)

type ModifierMiddleware struct {
	handler http.Handler
}

func (m *ModifierMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	rec := httptest.NewRecorder()
	// passing a ResponseRecorder instead of the original RW
	m.handler.ServeHTTP(rec, r)
	// after this finishes, we have the response recorded
	// and can modify it before copying it to the original RW

	// we copy the original headers first
	for k, v := range rec.Header() {
		w.Header()[k] = v
	}
	// and set an additional one
	w.Header().Set("X-We-Modified-This", "Yup")
	// only then the status code, as this call writes the headers as well 
	w.WriteHeader(418)
        // The body hasn't been written (to the real RW) yet,
        // so we can prepend some data.
        data := []byte("Middleware says hello again. ")

        // But the Content-Length might have been set already,
        // we should modify it by adding the length
        // of our own data.
        // Ignoring the error is fine here:
        // if Content-Length is empty or otherwise invalid,
        // Atoi() will return zero,
        // which is just what we'd want in that case.
        clen, _ := strconv.Atoi(r.Header.Get("Content-Length"))
        clen += len(data)
        w.Header.Set("Content-Length", strconv.Itoa(clen))

        // finally, write out our data
        w.Write(data)
	// then write out the original body
	w.Write(rec.Body.Bytes())
}

func myHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Success!"))
}

func main() {
	mid := &ModifierMiddleware{http.HandlerFunc(myHandler)}

	println("Listening on port 8080")
	http.ListenAndServe(":8080", mid)
}
package main

import (
	"net/http"
)

type AppendMiddleware struct {
	handler http.Handler
}

func (a *AppendMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	a.handler.ServeHTTP(w, r)
	w.Write([]byte("<!-- Middleware says hello! -->"))
}

func myHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Success!"))
}

func main() {
	mid := &AppendMiddleware{http.HandlerFunc(myHandler)}

	println("Listening on port 8080")
	http.ListenAndServe(":8080", mid)
}
package main

import (
	"net/http"
)

func SingleHost(handler http.Handler, allowedHost string) http.Handler {
	ourFunc := func(w http.ResponseWriter, r *http.Request) {
		host := r.Host
		if host == allowedHost {
			handler.ServeHTTP(w, r)
		} else {
			w.WriteHeader(403)
		}
	}
	return http.HandlerFunc(ourFunc)
}


func myHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Success!"))
}

func main() {
	single := SingleHost(http.HandlerFunc(myHandler), "example.com")

	println("Listening on port 8080")
	http.ListenAndServe(":8080", single)
}
package main

import (
	"net/http"
)

type SingleHost struct {
	handler     http.Handler
	allowedHost string
}

func NewSingleHost(handler http.Handler, allowedHost string) *SingleHost {
	return &SingleHost{handler: handler, allowedHost: allowedHost}
}

func (s *SingleHost) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	host := r.Host
	if host == s.allowedHost {
		s.handler.ServeHTTP(w, r)
	} else {
		w.WriteHeader(403)
	}
}

func myHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Success!"))
}

func main() {
	single := NewSingleHost(http.HandlerFunc(myHandler), "example.com")

	println("Listening on port 8080")
	http.ListenAndServe(":8080", single)
}

通过 HTTP 中间件验证 WebSocket 连接 - Golang

【中文标题】通过 HTTP 中间件验证 WebSocket 连接 - Golang【英文标题】:Authenticating WebSocket Connections via HTTP Middleware - Golang 【发布时间】:2018-10-14 22:47:41 【问题描述】:

问题陈述:

我正在尝试使用 Golang 中的基本中间件来保护 websocket 升级程序 http 端点,例如 the WebSocket protocol doesn’t handle authorization or authentication。

社区建议

    虽然含糊不清,但有些人建议“我建议使用应用程序的代码来验证升级握手以验证 HTTP 请求。” 还有人建议“连接后,客户端需要发送用户名和密码,需要服务器检查。如果不匹配,关闭连接”,但这似乎不习惯。

策略:

到目前为止,我失败的策略是尝试上面的社区策略 1,以通过中间件使用自定义标头 X-Api-Key 安全升级连接,并且只升级使用匹配密钥启动对话的客户端。

下面的代码在服务器端生成the client is not using the websocket protocol: 'upgrade' token not found in 'Connection' header

问:

我想在理解方面寻求帮助:

如果我对策略 1 的理解存在缺陷,我该如何改进它?似乎通过http发送初始身份验证GET,随后通过方案ws的升级请求被服务器拒绝。 如果策略 2 可行,如何实施?

想法和建议、示例、要点表示赞赏,如果我可以进一步澄清或重申,请提供建议。

server.go:

package main

import (
    "flag"
    "log"
    "net/http"

    "github.com/gorilla/websocket"
)

func main() 
    var addr = flag.String("addr", "localhost:8080", "http service address")
    flag.Parse()

    http.Handle("/ws", Middleware(
        http.HandlerFunc(wsHandler),
        authMiddleware,
    ))
    log.Printf("listening on %v", *addr)
    log.Fatal(http.ListenAndServe(*addr, nil))


func Middleware(h http.Handler, middleware ...func(http.Handler) http.Handler) http.Handler 
    for _, mw := range middleware 
        h = mw(h)
    
    return h


var upgrader = websocket.Upgrader
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,


func wsHandler(rw http.ResponseWriter, req *http.Request) 
    wsConn, err := upgrader.Upgrade(rw, req, nil)
    if err != nil 
        log.Printf("upgrade err: %v", err)
        return
    
    defer wsConn.Close()

    for 
        _, message, err := wsConn.ReadMessage()
        if err != nil 
            log.Printf("read err: %v", err)
            break
        
        log.Printf("recv: %s", message)
    


func authMiddleware(next http.Handler) http.Handler 
    TestApiKey := "test_api_key"
    return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) 
        var apiKey string
        if apiKey = req.Header.Get("X-Api-Key"); apiKey != TestApiKey 
            log.Printf("bad auth api key: %s", apiKey)
            rw.WriteHeader(http.StatusForbidden)
            return
        
        next.ServeHTTP(rw, req)
    )

client.go:

package main

import (
    "fmt"
    "log"
    "net/http"
    "net/url"

    "github.com/gorilla/websocket"
)

func main() 
    // auth first
    req, err := http.NewRequest("GET", "http://localhost:8080/ws", nil)
    if err != nil 
        log.Fatal(err)
    
    req.Header.Set("X-Api-Key", "test_api_key")

    resp, err := http.DefaultClient.Do(req)
    if err != nil || resp.StatusCode != http.StatusOK 
        log.Fatalf("auth err: %v", err)
    
    defer resp.Body.Close()

    // create ws conn
    u := url.URLScheme: "ws", Host: "localhost:8080", Path: "/ws"
    u.RequestURI()
    fmt.Printf("ws url: %s", u.String())
    log.Printf("connecting to %s", u.String())

    conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
    if err != nil 
        log.Fatalf("dial err: %v", err)
    

    err = conn.WriteMessage(websocket.TextMessage, []byte("hellow websockets"))
    if err != nil 
        log.Fatalf("msg err: %v", err)
    

【问题讨论】:

【参考方案1】:

问题中的客户端应用程序向 websocket 端点发送两个请求。第一个是经过身份验证的 HTTP 请求。此请求升级失败,因为它不是 websocket 握手。第二个请求是未经身份验证的 websocket 握手。此请求失败,因为它无法进行身份验证。

解决方法是发送经过身份验证的 websocket 握手。将 auth 标头通过最后一个参数传递给 Dial。

func main() 
    u := url.URLScheme: "ws", Host: "localhost:8080", Path: "/ws"
    conn, _, err := websocket.DefaultDialer.Dial(u.String(), http.Header"X-Api-Key": []string"test_api_key")
    if err != nil 
        log.Fatalf("dial err: %v", err)
    
    err = conn.WriteMessage(websocket.TextMessage, []byte("hellow websockets"))
    if err != nil 
        log.Fatalf("msg err: %v", err)
    

在服务器上,使用用于验证 HTTP 请求的应用程序代码验证握手。

【讨论】:

优秀的@ThunderCat,我怀疑将两个请求发送到同一个端点,但你对这个问题的阐述清楚地说明了为什么这不会像我一样工作。我将尝试您的解决方案并在验证后标记为接受。谢谢! 这个解决方案对我有用,接受答案。对于任何偶然发现这一点的人,都有一个小错字。 http 标头声明应为:http.Header"X-Api-Key": []string"test_api_key"

以上是关于golang 去我的博客文章中间件样本。 http://justinas.org/writing-http-middleware-in-go/的主要内容,如果未能解决你的问题,请参考以下文章

自己喜欢的几个前端框架

通过 HTTP 中间件验证 WebSocket 连接 - Golang

golang中可变长参数的使用

golang中可变长参数的使用

Golang Web入门:如何设计API

Golang Web入门:如何设计API