Building Middleware with Negroni

Reasons use middleware, including logging requests, authenticating and authorizing users, and mapping resources.

Idiomatic HTTP Middleware for Golang. https://github.com/urfave/negroni

Install the negroni package.

go get github.com/urfave/negroni

PS: How to solve the go get can not work in China. Following is the best solution so far. https://github.com/goproxy/goproxy.cn

$ go env -w GO111MODULE=on
$ go env -w GOPROXY=https://goproxy.cn,direct

Negroni example

package main

import (
"github.com/gorilla/mux"
"github.com/urfave/negroni"
"net/http"
) func main() {
r := mux.NewRouter()
n := negroni.Classic()
n.UseHandler(r)
http.ListenAndServe(":8000",n)
}

Build and execute this program.

Create trivial middleware that prints a message and passes execution to the next middleware in the chain:

package main

import (
"fmt"
"github.com/gorilla/mux"
"github.com/urfave/negroni"
"net/http"
) type trivial struct {
} func (t *trivial) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
fmt.Println("Executing trivial middleware")
next(w, r)
} func main() {
r := mux.NewRouter()
n := negroni.Classic()
n.UseHandler(r)
n.Use(&trivial{})
http.ListenAndServe(":8000",n)
}

Build and test this new program.

Adding Authentication with Negroni

Use of context, which can easily pass variables between functions.  

package main

import (
"context"
"fmt"
"net/http" "github.com/gorilla/mux"
"github.com/urfave/negroni"
) type badAuth struct {
Username string
Password string
} func (b *badAuth) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
username := r.URL.Query().Get("username")
password := r.URL.Query().Get("password")
if username != b.Username && password !=b.Password {
http.Error(w, "Unauthorized", 401)
return
}
ctx := context.WithValue(r.Context(), "username", username)
r = r.WithContext(ctx)
next(w, r)
} func hello(w http.ResponseWriter, r * http.Request) {
username := r.Context().Value("username").(string)
fmt.Fprintf(w, "Hi %s\n", username)
} func main() {
r := mux.NewRouter()
r.HandleFunc("/hello",hello).Methods("GET")
n := negroni.Classic()
n.Use(&badAuth{
Username: "admin",
Password: "password",
})
n.UseHandler(r)
http.ListenAndServe(":8000", n) }

Build and excute this program. Then test it by sending a few requests to the server.

curl -i http://localhost:8000/hello
curl -i 'http://localhost:8000/hello?username=admin&password=password'

Logs on the server-side.

Go Pentester - HTTP Servers(3)的更多相关文章

  1. Go Pentester - HTTP Servers(2)

    Routing with the gorilla/mux Package A powerful HTTP router and URL matcher for building Go web serv ...

  2. Go Pentester - HTTP Servers(1)

    HTTP Server Basics Use net/http package and useful third-party packages by building simple servers. ...

  3. Coping with the TCP TIME-WAIT state on busy Linux servers

    Coping with the TCP TIME-WAIT state on busy Linux servers 文章源自于:https://vincent.bernat.im/en/blog/20 ...

  4. How To Restart timer service on all servers in farm

    [array]$servers= Get-SPServer | ? {$_.Role -eq "Application"} $farm = Get-SPFarm foreach ( ...

  5. eclipse Run On Server 异常:could not load the Tomcat Server configuration at Servers\tomcat V5.0 Sertomcat

    eclipse Run On Server 异常:could not load the Tomcat Server configuration at Servers\tomcat V5.0 Serto ...

  6. coderforces #387 Servers(模拟)

    Servers time limit per test 2 seconds memory limit per test 256 megabytes input standard input outpu ...

  7. Servers

    Servers¶ Server interface. class novaclient.v1_1.servers.Server(manager, info, loaded=False) Bases: ...

  8. 使用servers 启动项目时 ,一直处于启动中, 最后出现无法的问题。

    使用eclipse 中的servers 配置了一个server 来启动项目, 发现无法启动 排除法: 去掉项目配置,单独启动该server ,发现可以启动, 说明是项目出现问题 但是项目并没有报错, ...

  9. servers中添加server时,看不到运行环境的选择。

    servers中添加server时,看不到运行环境的选择. 主要原因是tomcat目录中的配置文件格式不对.

随机推荐

  1. [置顶] linux中fork()函数详解(原创!!实例讲解)

    分类: 计算机系统 linux2010-06-01 23:35 60721人阅读 评论(105) 收藏 举报 linux2010存储  一.fork入门知识 一个进程,包括代码.数据和分配给进程的资源 ...

  2. MongoDB文档(二)--查询

    (一)查询文档 查询文档可以使用以下方法 # 以非结构化的方式显示所有的文档 db.<collectionName>.find(document) # 以结构化的方式显示所有文档 db.& ...

  3. 能被 K 整除的最大连续子串长度

    [来源]网上流传的2017美团秋招笔试题 [问题描述] 两个测试样例输出都是5 [算法思路] 暴力解法时间会超限,使用一种很巧妙的数学方法.用在读取数组arr时用数组sum记录其前 i 项的和,即 s ...

  4. Elasticsearch、Solr、Lucene、Hermes区别

    Elasticsearch简介 Elasticsearch是一个实时分布式搜索和分析引擎.它让你以前所未有的速度处理大数据成为可能.它用于全文搜索.结构化搜索.分析以及将这三者混合使用:维基百科使用E ...

  5. 微信小程序预览Word文档

    <view data-url="https://xxxcom/attachment/word.docx" data-type="docx" catchta ...

  6. css的四种使用方式

    方式一:内联样式 内联样式,也叫行内样式,指的是直接在style属性中添加CSS 示例: <DIV style="display: none;background:red"& ...

  7. express高效入门教程(3)

    3.路由 路由到底是什么呢?不管官方定义到底是什么,咱通俗的说就是根据不同的url,执行不同的代码,类似于编程语言中的分支结构 3.1.express规划路由 稍微复杂点的应用,通常都是分模块进行的, ...

  8. 关于线上一次DDOS攻击和阿里云DDOS防护相关内容

    问题 最近我们的一台阿里云服务器 (ECS,有公网IP,Nginx 服务器,开放了80,443),遭受到了DDOS攻击,主要攻击的行为是 攻击我们443 端口.发起大量的请求. 但是我们在 Nginx ...

  9. 09 . Prometheus监控tomcat+jvm

    List CentOS7.3 prometheus-2.2.1.linux-amd64.tar.gz redis_exporter-v0.30.0.linux-amd64.tar.gz 节点名 IP ...

  10. Nginx 从入门到放弃(三)

    今天来学习nginx的日志管理,并通过日志脚本来切割日志并保存. nginx日志管理 在nginx中设置日志格式  http {    log_format main  '$remote_addr - ...