93 lines
1.8 KiB
Go
93 lines
1.8 KiB
Go
package server
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"local/router"
|
|
"local/rssmon3/config"
|
|
"local/storage"
|
|
"log"
|
|
"net/http"
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
func (s *Server) Routes() error {
|
|
handles := []struct {
|
|
path string
|
|
handler http.HandlerFunc
|
|
}{
|
|
{path: fmt.Sprintf("/api/tag/%s", router.Wildcard), handler: s.tag},
|
|
}
|
|
for _, handle := range handles {
|
|
if err := s.router.Add(handle.path, handle.handler); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Server) notFound(w http.ResponseWriter, r *http.Request) {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
|
|
func (s *Server) userError(w http.ResponseWriter, r *http.Request, err error) {
|
|
status := http.StatusBadRequest
|
|
log.Printf("%d: %v", status, err)
|
|
w.WriteHeader(status)
|
|
}
|
|
|
|
func (s *Server) error(w http.ResponseWriter, r *http.Request, err error) {
|
|
status := http.StatusInternalServerError
|
|
log.Printf("%d: %v", status, err)
|
|
w.WriteHeader(status)
|
|
}
|
|
|
|
func (s *Server) tag(w http.ResponseWriter, r *http.Request) {
|
|
foo := s.notFound
|
|
switch r.Method {
|
|
case "GET":
|
|
foo = s.getFeedByTag
|
|
}
|
|
foo(w, r)
|
|
}
|
|
|
|
func (s *Server) getFeedByTag(w http.ResponseWriter, r *http.Request) {
|
|
tag := regexp.MustCompile("^.*\\/").ReplaceAllString(r.URL.Path, "")
|
|
log.Println(tag)
|
|
s.error(w, r, errors.New("not impl"))
|
|
}
|
|
|
|
func (s *Server) auctions(w http.ResponseWriter, r *http.Request) {
|
|
foo := http.NotFound
|
|
r.ParseForm()
|
|
switch strings.ToLower(r.Method) {
|
|
case "get":
|
|
foo = s.get
|
|
}
|
|
foo(w, r)
|
|
}
|
|
|
|
func (s *Server) get(w http.ResponseWriter, r *http.Request) {
|
|
db := config.Values().DB
|
|
if len(strings.Split(r.URL.Path, "/")) < 3 {
|
|
s.notFound(w, r)
|
|
return
|
|
}
|
|
key := strings.Split(r.URL.Path, "/")[2]
|
|
log.Println("GET", key)
|
|
value, err := db.Get(key)
|
|
if err == storage.ErrNotFound {
|
|
s.notFound(w, r)
|
|
return
|
|
}
|
|
if err != nil {
|
|
s.error(w, r, err)
|
|
return
|
|
}
|
|
io.Copy(w, bytes.NewBuffer(value))
|
|
}
|