Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func (handler *UserHandler) getUser(w http.ResponseWriter, ID int) {
- logfile, err := os.OpenFile("events.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
- if err != nil {
- log.Fatalf("Error opening file: %v", err)
- }
- defer logfile.Close()
- log.SetOutput(logfile)
- user := db.Fetch(ID)
- userJSON, err := json.Marshal(user)
- if err != nil {
- log.Printf("Error while marshaling the user into JSON: %v", err)
- return
- }
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusOK)
- // userJSON is sent as http Response
- w.Write(userJSON)
- }
- type UserHandler struct{}
- func (handle *UserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- var head string
- head, r.URL.Path = ShiftPath(r.URL.Path)
- id, err := strconv.Atoi(head)
- if err != nil {
- http.Error(w, fmt.Sprintf("Invalid user ID %q", head), http.StatusBadRequest)
- return
- }
- switch r.Method {
- case "GET":
- handle.getUser(w, id)
- default:
- http.Error(w, "Only GET is allowed", http.StatusMethodNotAllowed)
- }
- }
- func ShiftPath(p string) (head, tail string) {
- p = path.Clean("/" + p)
- i := strings.Index(p[1:], "/") + 1
- if i <= 0 {
- return p[1:], "/"
- }
- return p[1:i], p[i:]
- }
- func TestGetUser(t *testing.T) {
- handler := new(UserHandler)
- mux := http.NewServeMux()
- mux.HandleFunc("/user/", handler.ServeHTTP)
- writer := httptest.NewRecorder()
- request, _ := http.NewRequest("GET", "/user/12", nil)
- mux.ServeHTTP(writer, request)
- if writer.Code != 200 {
- t.Errorf("Response code is %v", writer.Code)
- }
- }
Add Comment
Please, Sign In to add comment