mgmt_api.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package server
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. )
  7. func StartManagementAPI(fs *FeedbagStore) {
  8. http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
  9. switch r.Method {
  10. case http.MethodGet:
  11. getUsers(fs, w, r)
  12. case http.MethodPost:
  13. createUser(fs, w, r)
  14. default:
  15. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  16. }
  17. })
  18. //todo make port configurable
  19. port := 8080
  20. fmt.Printf("Server is running on :%d...\n", port)
  21. if err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil); err != nil {
  22. panic(err)
  23. }
  24. }
  25. // getUsers handles the GET /user endpoint.
  26. func getUsers(fs *FeedbagStore, w http.ResponseWriter, r *http.Request) {
  27. w.Header().Set("Content-Type", "application/json")
  28. users, err := fs.Users()
  29. if err != nil {
  30. http.Error(w, err.Error(), http.StatusInternalServerError)
  31. return
  32. }
  33. if err := json.NewEncoder(w).Encode(users); err != nil {
  34. http.Error(w, err.Error(), http.StatusInternalServerError)
  35. return
  36. }
  37. }
  38. type CreateUser struct {
  39. User
  40. Password string `json:"password,omitempty"`
  41. }
  42. // createUser handles the POST /user endpoint.
  43. func createUser(fs *FeedbagStore, w http.ResponseWriter, r *http.Request) {
  44. var newUser CreateUser
  45. if err := json.NewDecoder(r.Body).Decode(&newUser); err != nil {
  46. http.Error(w, err.Error(), http.StatusBadRequest)
  47. return
  48. }
  49. // todo does the request contain authkey?
  50. newUser.HashPassword(newUser.Password)
  51. if err := fs.InsertUser(newUser.User); err != nil {
  52. http.Error(w, err.Error(), http.StatusInternalServerError)
  53. return
  54. }
  55. w.WriteHeader(http.StatusCreated)
  56. fmt.Fprintln(w, "User account created successfully.")
  57. }