httpbin

package module
v0.0.19 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2023 License: Apache-2.0 Imports: 22 Imported by: 0

README

go-httpbin

Read GoDoc

A Go handler that lets you test your HTTP client, retry logic, streaming behavior, timeouts etc. with the endpoints of [httpbin.org][ht] locally in a [net/http/httptest.Server][hts].

This way, you can write tests without relying on an external dependency like [httpbin.org][ht].

Endpoints

  • /ip Returns Origin IP.
  • /user-agent Returns user-agent.
  • /headers Returns headers.
  • /get Returns GET data.
  • /status/:code Returns given HTTP Status code.
  • /redirect/:n 302 Redirects n times.
  • /absolute-redirect/:n 302 Absolute redirects n times.
  • /redirect-to?url=foo 302 Redirects to the foo URL.
  • /stream/:n Streams n lines of JSON objects.
  • /delay/:n Delays responding for min(n, 10) seconds.
  • /bytes/:n Generates n random bytes of binary data, accepts optional seed integer parameter.
  • /cookies Returns the cookies.
  • /cookies/set?name=value Sets one or more simple cookies.
  • /cookies/delete?name Deletes one or more simple cookies.
  • /drip?numbytes=n&duration=s&delay=s&code=code Drips data over a duration after an optional initial delay, then optionally returns with the given status code.
  • /cache Returns 200 unless an If-Modified-Since or If-None-Match header is provided, when it returns a 304.
  • /cache/:n Sets a Cache-Control header for n seconds.
  • /gzip Returns gzip-encoded data.
  • /deflate Returns deflate-encoded data.
  • /brotli Returns brotli-encoded data.
  • /robots.txt Returns some robots.txt rules.
  • /deny Denied by robots.txt file.
  • /basic-auth/:user/:passwd Challenges HTTP Basic Auth.
  • /hidden-basic-auth/:user/:passwd Challenges HTTP Basic Auth and returns 404 on failure.
  • /html Returns some HTML.
  • /xml Returns some XML.
  • /image/gif Returns page containing an animated GIF image.
  • /image/png Returns page containing a PNG image.
  • /image/jpeg Returns page containing a JPEG image.

How to use

Standing up a Go server running httpbin endpoints is just 1 line:

package main

import (
    "log"
    "net/http"
    "github.com/AndriyKalashnykov/go-httpbin"
)

func main() {
	log.Fatal(http.ListenAndServe(":8080", httpbin.GetMux()))
}

Let's say you do not want a server running all the time because you just want to test your HTTP logic after all. Integrating httpbin to your tests is very simple:

package test

import (
    "testing"
    "net/http"
    "net/http/httptest"

    "github.com/AndriyKalashnykov/go-httpbin"
)

func TestDownload(t *testing.T) {
    srv := httptest.NewServer(httpbin.GetMux())
    defer srv.Close()

    resp, err := http.Get(srv.URL + "/bytes/65536")
    if err != nil {
        t.Fatal(err)
    }
    // read from an actual HTTP server hosted locally
    // test whatever you are going to test...
}

go-httpbin works from the command line as well:

$ go install github.com/AndriyKalashnykov/go-httpbin/cmd/httpbin
$ $GOPATH/bin/httpbin -host :8080

Documentation

Overview

Package httpbin providers HTTP handlers for httpbin.org endpoints and a multiplexer to directly hook it up to any http.Server or httptest.Server.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// BinaryChunkSize is buffer length used for stuff like generating
	// large blobs.
	BinaryChunkSize = 64 * 1024

	// DelayMax is the maximum execution time for /delay endpoint.
	DelayMax = 10 * time.Second

	// StreamInterval is the default interval between writing objects to the stream.
	StreamInterval = 1 * time.Second
)

Functions

func AbsoluteRedirectHandler

func AbsoluteRedirectHandler(w http.ResponseWriter, r *http.Request)

AbsoluteRedirectHandler returns a 302 Found response if n=1 pointing to /host/get, otherwise to /host/absolute-redirect/(n-1)

func BasicAuthHandler

func BasicAuthHandler(w http.ResponseWriter, r *http.Request)

BasicAuthHandler challenges with given username and password.

func BrotliHandler

func BrotliHandler(w http.ResponseWriter, r *http.Request)

BrotliHandler returns a Brotli-encoded response

func BytesHandler

func BytesHandler(w http.ResponseWriter, r *http.Request)

BytesHandler returns n random bytes of binary data and accepts an optional 'seed' integer query parameter.

func CacheHandler

func CacheHandler(w http.ResponseWriter, r *http.Request)

CacheHandler returns 200 with the response of /get unless an If-Modified-Since or If-None-Match header is provided, when it returns a 304.

func CookiesHandler

func CookiesHandler(w http.ResponseWriter, r *http.Request)

CookiesHandler returns the cookies provided in the request.

func DeflateHandler

func DeflateHandler(w http.ResponseWriter, r *http.Request)

DeflateHandler returns a DEFLATE-encoded response.

func DelayHandler

func DelayHandler(w http.ResponseWriter, r *http.Request)

DelayHandler delays responding for min(n, 10) seconds and responds with /get endpoint

func DeleteCookiesHandler

func DeleteCookiesHandler(w http.ResponseWriter, r *http.Request)

DeleteCookiesHandler deletes cookies with provided query value keys in the response by settings a Unix epoch expiration date and returns a 302 redirect to /cookies.

func DenyHandler

func DenyHandler(w http.ResponseWriter, r *http.Request)

DenyHandler returns a plain-text response.

func DripHandler

func DripHandler(w http.ResponseWriter, r *http.Request)

DripHandler drips data over a duration after an optional initial delay, then optionally returns with the given status code.

func GIFHandler

func GIFHandler(rw http.ResponseWriter, r *http.Request)

GIFHandler returns an animated GIF image. Source: http://tech.nitoyon.com/en/blog/2016/01/07/go-animated-gif-gen/

func GZIPHandler

func GZIPHandler(w http.ResponseWriter, r *http.Request)

GZIPHandler returns a GZIP-encoded response

func GetHandler

func GetHandler(w http.ResponseWriter, r *http.Request)

GetHandler returns user agent.

func GetMux

func GetMux() *mux.Router

GetMux returns the mux with handlers for httpbin endpoints registered.

Example (Httptest)
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httptest"

	httpbin "github.com/AndriyKalashnykov/go-httpbin"
)

func main() {
	srv := httptest.NewServer(httpbin.GetMux())
	defer srv.Close()

	resp, err := http.Get(srv.URL + "/bytes/65536")
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	// read from an actual HTTP server hosted locally
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Retrieved %d bytes.\n", len(b))
}
Output:

Retrieved 65536 bytes.
Example (Server)
package main

import (
	"log"
	"net/http"

	httpbin "github.com/AndriyKalashnykov/go-httpbin"
)

func main() {
	log.Fatal(http.ListenAndServe(":8080", httpbin.GetMux()))
}
Output:

func HTMLHandler

func HTMLHandler(w http.ResponseWriter, r *http.Request)

HTMLHandler returns some HTML response.

func HeadersHandler

func HeadersHandler(w http.ResponseWriter, r *http.Request)

HeadersHandler returns user agent.

func HiddenBasicAuthHandler

func HiddenBasicAuthHandler(w http.ResponseWriter, r *http.Request)

HiddenBasicAuthHandler challenges with given username and password and returns 404 if authentication fails.

func HomeHandler

func HomeHandler(w http.ResponseWriter, r *http.Request)

HomeHandler serves static HTML content for the index page.

func IPHandler

func IPHandler(w http.ResponseWriter, r *http.Request)

IPHandler returns Origin IP.

func JPEGHandler

func JPEGHandler(w http.ResponseWriter, r *http.Request)

JPEGHandler returns a JPEG image.

func PNGHandler

func PNGHandler(w http.ResponseWriter, r *http.Request)

PNGHandler returns a PNG image.

func PostHandler

func PostHandler(w http.ResponseWriter, r *http.Request)

PostHandler accept a post and echo its data back

func RedirectHandler

func RedirectHandler(w http.ResponseWriter, r *http.Request)

RedirectHandler returns a 302 Found response if n=1 pointing to /get, otherwise to /redirect/(n-1)

func RedirectToHandler

func RedirectToHandler(w http.ResponseWriter, r *http.Request)

RedirectToHandler returns a 302 Found response pointing to the url query parameter

func RobotsTXTHandler

func RobotsTXTHandler(w http.ResponseWriter, r *http.Request)

RobotsTXTHandler returns a robots.txt response.

func SetCacheHandler

func SetCacheHandler(w http.ResponseWriter, r *http.Request)

SetCacheHandler sets a Cache-Control header for n seconds and returns with the /get response.

func SetCookiesHandler

func SetCookiesHandler(w http.ResponseWriter, r *http.Request)

SetCookiesHandler sets the query key/value pairs as cookies in the response and returns a 302 redirect to /cookies.

func StatusHandler

func StatusHandler(w http.ResponseWriter, r *http.Request)

StatusHandler returns a proper response for provided status code

func StreamHandler

func StreamHandler(w http.ResponseWriter, r *http.Request)

StreamHandler writes a json object to a new line every second.

func UserAgentHandler

func UserAgentHandler(w http.ResponseWriter, r *http.Request)

UserAgentHandler returns user agent.

func XMLHandler

func XMLHandler(w http.ResponseWriter, r *http.Request)

XMLHandler returns some XML response.

Types

This section is empty.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL