test.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package login
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. )
  9. type User struct {
  10. UserID string `json:"user_id"`
  11. Password string `json:"password"`
  12. }
  13. func HelloGet(w http.ResponseWriter, r *http.Request) {
  14. log.Printf("Starting my hello world logging.")
  15. fmt.Fprint(w, "Hello, World!")
  16. }
  17. func MyWorld(w http.ResponseWriter, r *http.Request) {
  18. log.Printf(" My world logging.")
  19. fmt.Fprint(w, "My World!")
  20. }
  21. func Login(w http.ResponseWriter, r *http.Request) {
  22. log.Printf("Start login.")
  23. // Read body
  24. b, err := ioutil.ReadAll(r.Body)
  25. defer r.Body.Close()
  26. if err != nil {
  27. log.Printf("[ERROR] Read body.", err.Error())
  28. http.Error(w, err.Error(), 500)
  29. return
  30. }
  31. // Unmarshal
  32. var usr User
  33. err = json.Unmarshal(b, &usr)
  34. if err != nil {
  35. log.Printf("[ERROR] Unmarshal %s.", err.Error())
  36. http.Error(w, err.Error(), 500)
  37. return
  38. }
  39. log.Printf("Parse User login.", usr)
  40. bty, err := json.Marshal(usr)
  41. if err != nil {
  42. log.Printf("[ERROR] Marshal %s.", err.Error())
  43. http.Error(w, err.Error(), 500)
  44. return
  45. }
  46. fmt.Fprint(w, bty)
  47. log.Printf("End login.")
  48. }