Guest User

Untitled

a guest
Feb 15th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. func (handler *UserHandler) getUser(w http.ResponseWriter, ID int) {
  2.  
  3. logfile, err := os.OpenFile("events.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  4. if err != nil {
  5. log.Fatalf("Error opening file: %v", err)
  6. }
  7. defer logfile.Close()
  8. log.SetOutput(logfile)
  9.  
  10. user := db.Fetch(ID)
  11.  
  12. userJSON, err := json.Marshal(user)
  13. if err != nil {
  14. log.Printf("Error while marshaling the user into JSON: %v", err)
  15. return
  16. }
  17.  
  18. w.Header().Set("Content-Type", "application/json")
  19. w.WriteHeader(http.StatusOK)
  20.  
  21. // userJSON is sent as http Response
  22. w.Write(userJSON)
  23. }
  24.  
  25. type UserHandler struct{}
  26.  
  27. func (handle *UserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  28. var head string
  29. head, r.URL.Path = ShiftPath(r.URL.Path)
  30. id, err := strconv.Atoi(head)
  31. if err != nil {
  32. http.Error(w, fmt.Sprintf("Invalid user ID %q", head), http.StatusBadRequest)
  33. return
  34. }
  35. switch r.Method {
  36. case "GET":
  37. handle.getUser(w, id)
  38. default:
  39. http.Error(w, "Only GET is allowed", http.StatusMethodNotAllowed)
  40. }
  41. }
  42.  
  43. func ShiftPath(p string) (head, tail string) {
  44. p = path.Clean("/" + p)
  45. i := strings.Index(p[1:], "/") + 1
  46. if i <= 0 {
  47. return p[1:], "/"
  48. }
  49. return p[1:i], p[i:]
  50. }
  51.  
  52. func TestGetUser(t *testing.T) {
  53. handler := new(UserHandler)
  54. mux := http.NewServeMux()
  55. mux.HandleFunc("/user/", handler.ServeHTTP)
  56.  
  57. writer := httptest.NewRecorder()
  58. request, _ := http.NewRequest("GET", "/user/12", nil)
  59. mux.ServeHTTP(writer, request)
  60.  
  61. if writer.Code != 200 {
  62. t.Errorf("Response code is %v", writer.Code)
  63. }
  64. }
Add Comment
Please, Sign In to add comment