common.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package user
  2. import (
  3. "net/http"
  4. "errors"
  5. "strings"
  6. )
  7. //Send text response with given w and message as string
  8. func sendTextResponse(w http.ResponseWriter, msg string) {
  9. w.Write([]byte(msg))
  10. }
  11. //Send JSON response, with an extra json header
  12. func sendJSONResponse(w http.ResponseWriter, json string) {
  13. w.Header().Set("Content-Type", "application/json")
  14. w.Write([]byte(json))
  15. }
  16. func sendErrorResponse(w http.ResponseWriter, errMsg string) {
  17. w.Header().Set("Content-Type", "application/json")
  18. w.Write([]byte("{\"error\":\"" + errMsg + "\"}"))
  19. }
  20. func sendOK(w http.ResponseWriter) {
  21. w.Header().Set("Content-Type", "application/json")
  22. w.Write([]byte("\"OK\""))
  23. }
  24. /*
  25. The paramter move function (mv)
  26. You can find similar things in the PHP version of ArOZ Online Beta. You need to pass in
  27. r (HTTP Request Object)
  28. getParamter (string, aka $_GET['This string])
  29. Will return
  30. Paramter string (if any)
  31. Error (if error)
  32. */
  33. func mv(r *http.Request, getParamter string, postMode bool) (string, error) {
  34. if postMode == false {
  35. //Access the paramter via GET
  36. keys, ok := r.URL.Query()[getParamter]
  37. if !ok || len(keys[0]) < 1 {
  38. //log.Println("Url Param " + getParamter +" is missing")
  39. return "", errors.New("GET paramter " + getParamter + " not found or it is empty")
  40. }
  41. // Query()["key"] will return an array of items,
  42. // we only want the single item.
  43. key := keys[0]
  44. return string(key), nil
  45. } else {
  46. //Access the parameter via POST
  47. r.ParseForm()
  48. x := r.Form.Get(getParamter)
  49. if len(x) == 0 || x == "" {
  50. return "", errors.New("POST paramter " + getParamter + " not found or it is empty")
  51. }
  52. return string(x), nil
  53. }
  54. }
  55. func inSlice(list []string, a string) bool {
  56. for _, b := range list {
  57. if b == a {
  58. return true
  59. }
  60. }
  61. return false
  62. }
  63. func inSliceIgnoreCase(list []string, a string) bool {
  64. for _, b := range list {
  65. if strings.ToLower(b) == strings.ToLower(a) {
  66. return true
  67. }
  68. }
  69. return false
  70. }