todo-server/server/ajax/form/form.go

67 lines
1.1 KiB
Go
Executable File

package form
import (
"bytes"
"encoding/json"
"html"
"io"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
)
type readCloser struct {
io.Reader
}
func (rc readCloser) Close() error {
return nil
}
func GetAll(r *http.Request, k string) []string {
r.ParseForm()
v, _ := r.Form[k]
return v
}
func Get(r *http.Request, k string) string {
s := r.FormValue(k)
if s == "" {
b, _ := ioutil.ReadAll(r.Body)
var m map[string]json.RawMessage
if err := json.Unmarshal(b, &m); err != nil {
return ""
}
v, _ := m[k]
s = strings.TrimPrefix(strings.TrimSuffix(string(v), `"`), `"`)
r.Body = readCloser{bytes.NewReader(b)}
}
s = html.UnescapeString(s)
s = strings.ReplaceAll(s, "\r", "")
return s
}
func ToInt(s string) int {
v, _ := strconv.Atoi(s)
return v
}
func ToStrArr(k string) []string {
arr := strings.Split(k, ",")
outArr := []string{}
for i := range arr {
s := strings.TrimSpace(arr[i])
if len(s) > 0 {
outArr = append(outArr, s)
}
}
return outArr
}
func ToTime(s string) time.Time {
v, _ := time.Parse("2006-01-02 15:04:05", s)
return v
}