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.

  1. 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

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

Negroni example

  1. package main
  2.  
  3. import (
  4. "github.com/gorilla/mux"
  5. "github.com/urfave/negroni"
  6. "net/http"
  7. )
  8.  
  9. func main() {
  10. r := mux.NewRouter()
  11. n := negroni.Classic()
  12. n.UseHandler(r)
  13. http.ListenAndServe(":8000",n)
  14. }

Build and execute this program.

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

  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "github.com/gorilla/mux"
  6. "github.com/urfave/negroni"
  7. "net/http"
  8. )
  9.  
  10. type trivial struct {
  11. }
  12.  
  13. func (t *trivial) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
  14. fmt.Println("Executing trivial middleware")
  15. next(w, r)
  16. }
  17.  
  18. func main() {
  19. r := mux.NewRouter()
  20. n := negroni.Classic()
  21. n.UseHandler(r)
  22. n.Use(&trivial{})
  23. http.ListenAndServe(":8000",n)
  24. }

Build and test this new program.

Adding Authentication with Negroni

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

  1. package main
  2.  
  3. import (
  4. "context"
  5. "fmt"
  6. "net/http"
  7.  
  8. "github.com/gorilla/mux"
  9. "github.com/urfave/negroni"
  10. )
  11.  
  12. type badAuth struct {
  13. Username string
  14. Password string
  15. }
  16.  
  17. func (b *badAuth) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
  18. username := r.URL.Query().Get("username")
  19. password := r.URL.Query().Get("password")
  20. if username != b.Username && password !=b.Password {
  21. http.Error(w, "Unauthorized", 401)
  22. return
  23. }
  24. ctx := context.WithValue(r.Context(), "username", username)
  25. r = r.WithContext(ctx)
  26. next(w, r)
  27. }
  28.  
  29. func hello(w http.ResponseWriter, r * http.Request) {
  30. username := r.Context().Value("username").(string)
  31. fmt.Fprintf(w, "Hi %s\n", username)
  32. }
  33.  
  34. func main() {
  35. r := mux.NewRouter()
  36. r.HandleFunc("/hello",hello).Methods("GET")
  37. n := negroni.Classic()
  38. n.Use(&badAuth{
  39. Username: "admin",
  40. Password: "password",
  41. })
  42. n.UseHandler(r)
  43. http.ListenAndServe(":8000", n)
  44.  
  45. }

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

  1. curl -i http://localhost:8000/hello
  2. 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. php 判断设备是手机还是平板还是pc

    1 <?php 2 //获取USER AGENT 3 $agent = strtolower($_SERVER['HTTP_USER_AGENT']); 4 5 //分析数据 6 $is_pc ...

  2. php读取富文本处理html标签问题

    thinkphp的一项配置会将富文本编辑器的内容中的html标签进行转义处理 'DEFAULT_FILTER' => 'htmlspecialchars', // 默认参数过滤方法使用htmls ...

  3. 一个老牌程序员说:做Java开发,怎么可以不会这 20 种类库和 API

  4. c++虚函数和虚继承

    关键字virtual用于父类方法,如果传了一个子类对象,并且子类重写了父类的这个virtual方法,就会调用子类的方法.传谁就调用谁,这个就是多态.#include<iostream> u ...

  5. Linux系统结构详解(转)

    Linux系统一般有4个主要部分: 内核.shell.文件系统和应用程序.内核.shell和文件系统一起形成了基本的操作系统结构,它们使得用户可以运行程序.管理文件并使用系统.部分层次结构如图1-1所 ...

  6. springMvc接口开发--对访问的restful api接口进行拦截实现功能扩展

    1.视频参加Spring Security开发安全的REST服务\PART1\PART1 3-7 使用切片拦截REST服务三通it学院-www.santongit.com-.mp4 讲的比较的经典,后 ...

  7. Plugns

    Lombok Translation Rainbow Brackets

  8. 一场由yield引发的连串拷问

    最近在学习Python中生成器时,遇到了一个yield关键词,廖雪峰老师的官网中也没有详细的解释,经过一番查阅和研究,终于对它有了一些认识并做了总结(如有不对之处,还请大神指正). 首先先简单了解下生 ...

  9. 入门大数据---Flink开发环境搭建

    一.安装 Scala 插件 Flink 分别提供了基于 Java 语言和 Scala 语言的 API ,如果想要使用 Scala 语言来开发 Flink 程序,可以通过在 IDEA 中安装 Scala ...

  10. MongoDB入门四

    MongoDB针对实时位置 db.CallRecordInfo.find().count()db.SendInfo.find().count()db.RiderReaTimePositon.find( ...