vinxi / intercept

HTTP traffic interceptor and modifier made easy
MIT License
3 stars 2 forks source link

intercept Build Status GitHub release GoDoc Coverage Status Go Report Card

Middleware to easily intercept and/or modify HTTP requests/responses before sending them to the client/server.

Installation

go get -u gopkg.in/vinxi/intercept.v0

API

See the godoc reference for detailed API documentation.

Examples

Response interceptor and modifier

package main

import (
  "fmt"
  "gopkg.in/vinxi/intercept.v0"
  "gopkg.in/vinxi/vinxi.v0"
  "strings"
)

func main() {
  fmt.Printf("Server listening on port: %d\n", 3100)
  vs := vinxi.NewServer(vinxi.ServerOptions{Host: "localhost", Port: 3100})

  // Intercept request and modify URI path
  vs.Use(intercept.Request(func(req *intercept.RequestModifier) {
    req.Request.RequestURI = "/html"
  }))

  // Intercept and replace response body
  vs.Use(intercept.Response(func(res *intercept.ResponseModifier) {
    data, _ := res.ReadString()
    str := strings.Replace(data, "Herman Melville - Moby-Dick", "A Long History", 1)
    res.String(str)
  }))

  vs.Forward("http://httpbin.org")

  err := vs.Listen()
  if err != nil {
    fmt.Errorf("Error: %s\n", err)
  }
}

License

MIT