ribbit/endpoints_api_users.go

142 lines
2.3 KiB
Go
Raw Normal View History

2018-04-26 11:53:03 +00:00
package main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/gorilla/mux"
)
func handleApiUsersCall(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(req)
uid, uidok := vars["uid"]
fn, fnok := vars["function"]
switch req.Method {
case "GET":
if !uidok {
handleApiListUsers(w)
return
}
switch fn {
case "byname":
handleApiShowUserByName(uid, w)
2018-04-26 11:53:03 +00:00
default:
handleApiShowUser(uid, w)
}
case "POST", "PUT":
if !uidok {
userError(w)
2018-04-26 11:53:03 +00:00
return
}
if !fnok {
// Creating a new user
var u *User
var err error
if u, err = m.GetUserByName(uid); err == nil {
userError(w)
2018-04-26 11:53:03 +00:00
return
}
u = NewUser(uid)
m.SaveUser(u)
m.LoadUsers()
handleApiShowUser(u.Uuid, w)
return
}
switch fn {
case "slugs":
slug, slugok := vars["slug"]
if !slugok {
userError(w)
2018-04-26 11:53:03 +00:00
return
}
handleApiSubUser(uid, slug, w)
default:
userError(w)
2018-04-26 11:53:03 +00:00
return
}
default:
userError(w)
2018-04-26 11:53:03 +00:00
return
}
}
func handleApiListUsers(w http.ResponseWriter) {
var res []byte
var err error
if res, err = json.Marshal(m.Users); err != nil {
serverError(w)
2018-04-26 11:53:03 +00:00
return
}
fmt.Fprint(w, string(res))
}
func handleApiShowUser(uid string, w http.ResponseWriter) {
var err error
var u *User
if u, err = m.GetUser(uid); err != nil {
userError(w)
2018-04-26 11:53:03 +00:00
return
}
var res []byte
if res, err = json.Marshal(u); err != nil {
userError(w)
return
}
fmt.Fprint(w, string(res))
return
}
func handleApiShowUserByName(uname string, w http.ResponseWriter) {
var err error
var u *User
if u, err = m.GetUserByName(uname); err != nil {
userError(w)
return
}
var res []byte
if res, err = json.Marshal(u); err != nil {
userError(w)
2018-04-26 11:53:03 +00:00
return
}
fmt.Fprint(w, string(res))
return
}
func handleApiSubUser(uid string, slug string, w http.ResponseWriter) {
fmt.Println("Sub User", uid, slug)
var u *User
var err error
if u, err = m.GetUser(uid); err != nil {
userError(w)
2018-04-26 11:53:03 +00:00
return
}
pts := strings.Split(slug, ";")
if len(pts) != 2 {
userError(w)
2018-04-26 11:53:03 +00:00
return
}
2019-01-10 16:39:42 +00:00
//_, err = m.GetComic(pts[0], pts[1])
2018-04-26 11:53:03 +00:00
if err != nil {
userError(w)
2018-04-26 11:53:03 +00:00
return
}
u.SubSlugs = append(u.SubSlugs, slug)
err = m.SaveUser(u)
if err != nil {
userError(w)
2018-04-26 11:53:03 +00:00
return
}
m.LoadUsers()
handleApiShowUser(u.Uuid, w)
}