2020-06-05 04:10:50 +00:00
|
|
|
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package tsweb
|
|
|
|
|
|
|
|
import (
|
2022-02-07 18:01:23 +00:00
|
|
|
"bytes"
|
|
|
|
"compress/gzip"
|
2020-06-05 04:10:50 +00:00
|
|
|
"encoding/json"
|
2020-09-17 12:56:14 +00:00
|
|
|
"fmt"
|
2022-02-07 18:01:23 +00:00
|
|
|
"io/ioutil"
|
2020-06-05 04:10:50 +00:00
|
|
|
"net/http"
|
2022-02-07 18:01:23 +00:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"go4.org/mem"
|
2020-06-05 04:10:50 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type response struct {
|
|
|
|
Status string `json:"status"`
|
|
|
|
Error string `json:"error,omitempty"`
|
|
|
|
Data interface{} `json:"data,omitempty"`
|
|
|
|
}
|
|
|
|
|
2020-09-17 12:56:14 +00:00
|
|
|
// JSONHandlerFunc is an HTTP ReturnHandler that writes JSON responses to the client.
|
|
|
|
//
|
|
|
|
// Return a HTTPError to show an error message, otherwise JSONHandlerFunc will
|
2020-11-10 14:52:26 +00:00
|
|
|
// only report "internal server error" to the user with status code 500.
|
2020-08-18 21:37:01 +00:00
|
|
|
type JSONHandlerFunc func(r *http.Request) (status int, data interface{}, err error)
|
2020-06-05 04:10:50 +00:00
|
|
|
|
2020-09-17 12:56:14 +00:00
|
|
|
// ServeHTTPReturn implements the ReturnHandler interface.
|
2020-06-05 04:10:50 +00:00
|
|
|
//
|
2020-08-18 21:37:01 +00:00
|
|
|
// Use the following code to unmarshal the request body
|
2020-09-17 12:56:14 +00:00
|
|
|
//
|
2020-08-18 21:37:01 +00:00
|
|
|
// body := new(DataType)
|
|
|
|
// if err := json.NewDecoder(r.Body).Decode(body); err != nil {
|
|
|
|
// return http.StatusBadRequest, nil, err
|
|
|
|
// }
|
2020-06-05 04:10:50 +00:00
|
|
|
//
|
2020-11-10 14:52:26 +00:00
|
|
|
// See jsonhandler_test.go for examples.
|
2020-09-17 12:56:14 +00:00
|
|
|
func (fn JSONHandlerFunc) ServeHTTPReturn(w http.ResponseWriter, r *http.Request) error {
|
2020-08-18 21:37:01 +00:00
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
var resp *response
|
|
|
|
status, data, err := fn(r)
|
2020-11-10 14:52:26 +00:00
|
|
|
if err != nil {
|
2020-08-18 21:37:01 +00:00
|
|
|
if werr, ok := err.(HTTPError); ok {
|
|
|
|
resp = &response{
|
|
|
|
Status: "error",
|
|
|
|
Error: werr.Msg,
|
|
|
|
Data: data,
|
2020-06-05 04:10:50 +00:00
|
|
|
}
|
2020-09-17 12:56:14 +00:00
|
|
|
// Unwrap the HTTPError here because we are communicating with
|
|
|
|
// the client in this handler. We don't want the wrapping
|
|
|
|
// ReturnHandler to do it too.
|
|
|
|
err = werr.Err
|
2020-09-17 13:56:12 +00:00
|
|
|
if werr.Msg != "" {
|
|
|
|
err = fmt.Errorf("%s: %w", werr.Msg, err)
|
|
|
|
}
|
2020-11-10 14:52:26 +00:00
|
|
|
// take status from the HTTPError to encourage error handling in one location
|
|
|
|
if status != 0 && status != werr.Code {
|
|
|
|
err = fmt.Errorf("[unexpected] non-zero status that does not match HTTPError status, status: %d, HTTPError.code: %d: %w", status, werr.Code, err)
|
|
|
|
}
|
|
|
|
status = werr.Code
|
2020-08-18 21:37:01 +00:00
|
|
|
} else {
|
2020-11-10 14:52:26 +00:00
|
|
|
status = http.StatusInternalServerError
|
2020-08-18 21:37:01 +00:00
|
|
|
resp = &response{
|
|
|
|
Status: "error",
|
|
|
|
Error: "internal server error",
|
2020-06-05 04:10:50 +00:00
|
|
|
}
|
|
|
|
}
|
2020-11-10 14:52:26 +00:00
|
|
|
} else if status == 0 {
|
|
|
|
status = http.StatusInternalServerError
|
|
|
|
resp = &response{
|
|
|
|
Status: "error",
|
|
|
|
Error: "internal server error",
|
|
|
|
}
|
|
|
|
} else if err == nil {
|
|
|
|
resp = &response{
|
|
|
|
Status: "success",
|
|
|
|
Data: data,
|
|
|
|
}
|
2020-08-18 21:37:01 +00:00
|
|
|
}
|
2020-06-09 21:40:45 +00:00
|
|
|
|
2020-09-17 12:56:14 +00:00
|
|
|
b, jerr := json.Marshal(resp)
|
|
|
|
if jerr != nil {
|
2020-08-18 21:37:01 +00:00
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
w.Write([]byte(`{"status":"error","error":"json marshal error"}`))
|
2020-09-17 12:56:14 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("%w, and then we could not respond: %v", err, jerr)
|
|
|
|
}
|
|
|
|
return jerr
|
2020-08-18 21:37:01 +00:00
|
|
|
}
|
|
|
|
|
2022-02-07 18:01:23 +00:00
|
|
|
if AcceptsEncoding(r, "gzip") {
|
|
|
|
encb, err := gzipBytes(b)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
w.Header().Set("Content-Encoding", "gzip")
|
|
|
|
w.Header().Set("Content-Length", strconv.Itoa(len(encb)))
|
2022-02-09 20:06:27 +00:00
|
|
|
w.WriteHeader(status)
|
2022-02-07 18:01:23 +00:00
|
|
|
w.Write(encb)
|
|
|
|
} else {
|
|
|
|
w.Header().Set("Content-Length", strconv.Itoa(len(b)))
|
|
|
|
w.WriteHeader(status)
|
|
|
|
w.Write(b)
|
|
|
|
}
|
2020-09-17 12:56:14 +00:00
|
|
|
return err
|
2020-06-05 04:10:50 +00:00
|
|
|
}
|
2022-02-07 18:01:23 +00:00
|
|
|
|
|
|
|
var gzWriterPool sync.Pool // of *gzip.Writer
|
|
|
|
|
|
|
|
// gzipBytes returns the gzipped encoding of b.
|
|
|
|
func gzipBytes(b []byte) (zb []byte, err error) {
|
|
|
|
var buf bytes.Buffer
|
|
|
|
zw, ok := gzWriterPool.Get().(*gzip.Writer)
|
|
|
|
if ok {
|
|
|
|
zw.Reset(&buf)
|
|
|
|
} else {
|
|
|
|
zw = gzip.NewWriter(&buf)
|
|
|
|
}
|
|
|
|
defer gzWriterPool.Put(zw)
|
|
|
|
if _, err := zw.Write(b); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if err := zw.Close(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
zb = buf.Bytes()
|
|
|
|
zw.Reset(ioutil.Discard)
|
|
|
|
return zb, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// AcceptsEncoding reports whether r accepts the named encoding
|
|
|
|
// ("gzip", "br", etc).
|
|
|
|
func AcceptsEncoding(r *http.Request, enc string) bool {
|
|
|
|
h := r.Header.Get("Accept-Encoding")
|
|
|
|
if h == "" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if !strings.Contains(h, enc) && !mem.ContainsFold(mem.S(h), mem.S(enc)) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
remain := h
|
|
|
|
for len(remain) > 0 {
|
|
|
|
var part string
|
2022-03-16 21:25:31 +00:00
|
|
|
part, remain, _ = strings.Cut(remain, ",")
|
2022-02-07 18:01:23 +00:00
|
|
|
part = strings.TrimSpace(part)
|
2022-03-16 21:25:31 +00:00
|
|
|
part, _, _ = strings.Cut(part, ";")
|
2022-02-07 18:01:23 +00:00
|
|
|
if part == enc {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|