dm
/
vain
forked from sm/vain
1
0
Fork 0
vain/server.go

62 lines
1.7 KiB
Go
Raw Normal View History

2016-02-11 11:57:16 -08:00
package vain
2016-02-08 00:15:22 -08:00
2016-02-11 12:12:13 -08:00
import (
"encoding/json"
2016-02-11 12:12:13 -08:00
"fmt"
"net/http"
"strings"
2016-02-11 12:12:13 -08:00
)
2016-02-08 00:15:22 -08:00
type Server struct {
hostname string
storage *MemStore
2016-02-08 00:15:22 -08:00
}
2016-02-11 12:12:13 -08:00
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
switch req.Method {
case "GET":
fmt.Fprintf(w, "<!DOCTYPE html>\n<html><head>\n")
for _, p := range s.storage.All() {
fmt.Fprintf(w, "%s\n", p)
}
fmt.Fprintf(w, "</head>\n</html>\n")
2016-02-11 12:12:13 -08:00
case "POST":
if req.URL.Path == "/" {
http.Error(w, fmt.Sprintf("invalid path %q", req.URL.Path), http.StatusBadRequest)
return
}
p := Package{}
if err := json.NewDecoder(req.Body).Decode(&p); err != nil {
http.Error(w, fmt.Sprintf("unable to parse json from body: %v", err), http.StatusInternalServerError)
return
}
p.Path = fmt.Sprintf("%s/%s", s.hostname, strings.Trim(req.URL.Path, "/"))
if !Valid(p.Path, s.storage.All()) {
http.Error(w, fmt.Sprintf("invalid path; prefix already taken %q", req.URL.Path), http.StatusConflict)
return
}
if err := s.storage.Add(p); err != nil {
http.Error(w, fmt.Sprintf("unable to add package: %v", err), http.StatusInternalServerError)
return
}
if err := s.storage.Save(); err != nil {
http.Error(w, fmt.Sprintf("unable to store db: %v", err), http.StatusInternalServerError)
if err := s.storage.Remove(p.Path); err != nil {
fmt.Fprintf(w, "to add insult to injury, could not delete package: %v\n", err)
}
return
}
2016-02-11 12:12:13 -08:00
default:
2016-02-14 21:46:12 -08:00
http.Error(w, fmt.Sprintf("unsupported method %q; accepted: POST, GET", req.Method), http.StatusMethodNotAllowed)
2016-02-11 12:12:13 -08:00
}
}
func NewServer(sm *http.ServeMux, ms *MemStore, hostname string) *Server {
s := &Server{
storage: ms,
hostname: hostname,
}
2016-02-11 12:12:13 -08:00
sm.Handle("/", s)
2016-02-08 00:15:22 -08:00
return s
}