mgmt_api.go 1.7 KB

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