watchman/server/httpr.go

61 lines
1.2 KiB
Go
Executable File

package main
import (
"errors"
"fmt"
"io/ioutil"
"local/encryptor"
"log"
"net/http"
"path"
"strings"
)
type HTTPRequest struct {
w http.ResponseWriter
r *http.Request
body string
}
func (httpr *HTTPRequest) PathAdvance() string {
p := path.Clean("/" + httpr.r.URL.Path)
i := strings.Index(p[1:], "/") + 1
if i <= 0 {
httpr.r.URL.Path = "/"
return p[1:]
}
httpr.r.URL.Path = p[i:]
return p[1:i]
}
func (httpr *HTTPRequest) result(status int, err error, body interface{}) {
if err != nil {
log.Print(err)
}
httpr.w.WriteHeader(status)
if body != nil {
fmt.Fprintln(httpr.w, body)
}
}
func (httpr *HTTPRequest) limitReader(n ...int) ([]byte, error) {
if len(n) < 1 {
return ioutil.ReadAll(http.MaxBytesReader(nil, httpr.r.Body, int64(2048)))
}
return ioutil.ReadAll(http.MaxBytesReader(nil, httpr.r.Body, int64(n[0])))
}
func (httpr *HTTPRequest) readBody(enc encryptor.Encryptor) error {
body, err := httpr.limitReader()
if err != nil {
httpr.result(http.StatusRequestEntityTooLarge, err, nil)
return err
}
httpr.body = enc.Decrypt(string(body))
if httpr.body == "" {
httpr.result(secretError, nil, nil)
return errors.New("wrong pub key")
}
return nil
}