-
Notifications
You must be signed in to change notification settings - Fork 2
/
util.go
61 lines (55 loc) · 1.79 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
import (
"encoding/json"
"errors"
"net/http"
"strings"
)
func parseUser(r *http.Request, required map[string]struct{}) (User, error) {
var uc User
if strings.Contains(r.Header.Get("Content-Type"), "application/x-www-form-urlencoded") {
r.ParseForm()
username := r.PostForm.Get("username")
password := r.PostForm.Get("password")
fs := r.PostForm.Get("fs")
group := r.PostForm.Get("groupname")
uc = User{username, password, fs, group}
} else if strings.Contains(r.Header.Get("Content-Type"), "application/json") {
decoder := json.NewDecoder(r.Body)
decoder.Decode(&uc)
} else {
return User{}, errors.New("could not parse user (invalid format)")
}
// Validate user
if _, ok := required["username"]; ok && uc.Username == "" {
return User{}, errors.New("could not parse user. (no username supplied)")
}
if _, ok := required["password"]; ok && uc.Password == "" {
return User{}, errors.New("could not parse user. (no password supplied)")
}
if _, ok := required["fs"]; ok && uc.Fs == "" {
return User{}, errors.New("could not parse user. (no fs supplied)")
}
if _, ok := required["group"]; ok && uc.Group == "" {
return User{}, errors.New("could not parse user. (no group supplied)")
}
return uc, nil
}
func parseGroup(r *http.Request) (string, error) {
var name string
if strings.Contains(r.Header.Get("Content-Type"), "application/x-www-form-urlencoded") {
r.ParseForm()
name = r.PostForm.Get("groupname")
} else if strings.Contains(r.Header.Get("Content-Type"), "application/json") {
var uc Group
decoder := json.NewDecoder(r.Body)
decoder.Decode(&uc)
name = uc.Name
} else {
return "", errors.New("could not parse group (invalid format)")
}
if name == "" {
return "", errors.New("could not parse user (no groupname supplied)")
}
return name, nil
}