Select Git revision
handlers.go
-
Will McCutchen authoredWill McCutchen authored
handlers.go 11.16 KiB
package httpbin
import (
"bytes"
"compress/flate"
"compress/gzip"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
)
var acceptedMediaTypes = []string{
"image/webp",
"image/svg+xml",
"image/jpeg",
"image/png",
"image/",
}
// Index renders an HTML index page
func (h *HTTPBin) Index(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
writeHTML(w, MustAsset("index.html"), http.StatusOK)
}
// FormsPost renders an HTML form that submits a request to the /post endpoint
func (h *HTTPBin) FormsPost(w http.ResponseWriter, r *http.Request) {
writeHTML(w, MustAsset("forms-post.html"), http.StatusOK)
}
// UTF8 renders an HTML encoding stress test
func (h *HTTPBin) UTF8(w http.ResponseWriter, r *http.Request) {
writeHTML(w, MustAsset("utf8.html"), http.StatusOK)
}
// Get handles HTTP GET requests
func (h *HTTPBin) Get(w http.ResponseWriter, r *http.Request) {
resp := &getResponse{
Args: r.URL.Query(),
Headers: r.Header,
Origin: getOrigin(r),
URL: getURL(r).String(),
}
body, _ := json.Marshal(resp)
writeJSON(w, body, http.StatusOK)
}
// RequestWithBody handles POST, PUT, and PATCH requests
func (h *HTTPBin) RequestWithBody(w http.ResponseWriter, r *http.Request) {
resp := &bodyResponse{
Args: r.URL.Query(),
Headers: r.Header,
Origin: getOrigin(r),
URL: getURL(r).String(),
}
err := parseBody(w, r, resp, h.options.MaxMemory)
if err != nil {
http.Error(w, fmt.Sprintf("error parsing request body: %s", err), http.StatusBadRequest)
return
}
body, _ := json.Marshal(resp)
writeJSON(w, body, http.StatusOK)