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. 【Laravel】 常用的artisan命令

    全局篇 查看artisan命令php artisanphp artisan list 查看某个帮助命令php artisan help make:model 查看laravel版本php artisa ...

  2. EPLAN文本输入怎么转行,路径功能文本换行方法

    EPLAN文本输入怎么转行,路径功能文本换行方法 在输入文本时,按CTRL+ENTER可以将字体换行 Ctrl+回车键

  3. 我是如何从零学习开发一款跨平台桌面软件的(Markdown编辑器)

    [本文版权归微信公众号"代码艺术"(ID:onblog)所有,若是转载请务必保留本段原创声明,违者必究.若是文章有不足之处,欢迎关注微信公众号私信与我进行交流!] 原始冲动 最近一 ...

  4. 关于日期格式你必须知道的坑( yyyy-MM-dd HH:mm:ss)

    java中的的日期格式为: yyyy-MM-dd HH:mm:ss:代表将时间转换为24小时制,例: 2018-06-27 15:24:21yyyy-MM-dd hh:mm:ss:代表将时间转换为12 ...

  5. Linux软件服务管理

    学习该课程之前先学习linux的软件安装管理 1.linux的运行级别有下面几种类型 在后面的服务启动管理之中会被使用到 [root@weiyuan httpd-2.4.20]# runlevel N ...

  6. 5、struct2使用登陆的时候重定向功能,如果没有登陆,重定向到登陆页面

    1.实现这样一份功能,列如用户在进行某些操作的时候,如果没有登陆重定向到登陆页面 首先:我们创建一个功能操作页面,用户准备在该页面执行某些操作 在index.jsp中 <%@ page lang ...

  7. Flask-install-python2.6

    命令: # 安装virtualenv $ sudo yum install python-setuptools $ sudo easy_install virtualenv OR sudo pip i ...

  8. GDI+ 双缓冲实现

    早前曾为此问题在CSDN发帖求助(GDI+ 如何使用双缓冲绘制图像),得到了一个GDI+下较可行的方法,虽然绘制效果比直接绘制要好一些,不过还不能跟GDI的双缓冲方式比肩.   现在,我终于找到了一个 ...

  9. InfluxDB时序数据库基本知识

    InfluxDB是一个由InfluxData开发的开源时序型数据.它由Go写成,着力于高性能地查询与存储时序型数据.InfluxDB被广泛应用于存储系统的监控数据,IoT行业的实时数据等场景. 安装下 ...

  10. 《UNIX环境高级编程》(APUE) 笔记第八章 - 进程控制

    8 - 进程控制 Github 地址 1. 进程标识 每个进程都有一个非负整型表示的 唯一进程 ID .进程 ID 是可复用的(延迟复用算法). ID 为 \(0\) 的进程通常是调度进程,常常被称为 ...