92 lines
1.5 KiB
Go
92 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gorilla/mux"
|
|
)
|
|
|
|
func handleApiComicsCall(w http.ResponseWriter, req *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
vars := mux.Vars(req)
|
|
cid, cidok := vars["cid"]
|
|
fn, fnok := vars["function"]
|
|
switch req.Method {
|
|
case "GET":
|
|
if !cidok {
|
|
handleApiListComics(w)
|
|
return
|
|
}
|
|
if !fnok {
|
|
handleApiShowComic(cid, w)
|
|
return
|
|
}
|
|
switch fn {
|
|
case "search":
|
|
handleApiSearchComic(cid, w)
|
|
return
|
|
|
|
default:
|
|
userError(w)
|
|
return
|
|
}
|
|
|
|
default:
|
|
userError(w)
|
|
return
|
|
}
|
|
}
|
|
|
|
func handleApiListComics(w http.ResponseWriter) {
|
|
var res []byte
|
|
var err error
|
|
if res, err = json.Marshal(m.Comics); err != nil {
|
|
serverError(w)
|
|
return
|
|
}
|
|
fmt.Fprint(w, string(res))
|
|
}
|
|
|
|
func handleApiSearchComic(nm string, w http.ResponseWriter) {
|
|
nm = strings.ToLower(nm)
|
|
var cs []Comic
|
|
for _, c := range m.Comics {
|
|
if strings.Contains(strings.ToLower(c.Name), nm) {
|
|
cs = append(cs, c)
|
|
}
|
|
}
|
|
var res []byte
|
|
var err error
|
|
if res, err = json.Marshal(cs); err != nil {
|
|
serverError(w)
|
|
return
|
|
}
|
|
fmt.Fprint(w, string(res))
|
|
}
|
|
|
|
func handleApiShowComic(cid string, w http.ResponseWriter) {
|
|
var err error
|
|
var c *Comic
|
|
pts := strings.Split(cid, ";")
|
|
if len(pts) != 2 {
|
|
userError(w)
|
|
return
|
|
}
|
|
if c, err = m.GetComic(pts[0], pts[1]); err != nil {
|
|
userError(w)
|
|
return
|
|
}
|
|
|
|
var res []byte
|
|
if res, err = json.Marshal(c); err != nil {
|
|
userError(w)
|
|
return
|
|
}
|
|
fmt.Fprint(w, string(res))
|
|
return
|
|
}
|