nodeHttpController.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. package controller
  2. import (
  3. "github.com/gravitl/netmaker/models"
  4. "github.com/gravitl/netmaker/functions"
  5. "github.com/gravitl/netmaker/mongoconn"
  6. "golang.org/x/crypto/bcrypt"
  7. "time"
  8. "strings"
  9. "fmt"
  10. "context"
  11. "encoding/json"
  12. "log"
  13. "net/http"
  14. "github.com/gorilla/mux"
  15. "go.mongodb.org/mongo-driver/bson"
  16. "go.mongodb.org/mongo-driver/mongo/options"
  17. )
  18. func nodeHandlers(r *mux.Router) {
  19. r.HandleFunc("/api/{group}/nodes", authorize(true, "group", http.HandlerFunc(getGroupNodes))).Methods("GET")
  20. r.HandleFunc("/api/nodes", authorize(false, "master", http.HandlerFunc(getAllNodes))).Methods("GET")
  21. r.HandleFunc("/api/{group}/peerlist", authorize(true, "group", http.HandlerFunc(getPeerList))).Methods("GET")
  22. r.HandleFunc("/api/{group}/lastmodified", authorize(true, "group", http.HandlerFunc(getLastModified))).Methods("GET")
  23. r.HandleFunc("/api/{group}/nodes/{macaddress}", authorize(true, "node", http.HandlerFunc(getNode))).Methods("GET")
  24. r.HandleFunc("/api/{group}/nodes", createNode).Methods("POST")
  25. r.HandleFunc("/api/{group}/nodes/{macaddress}", authorize(true, "node", http.HandlerFunc(updateNode))).Methods("PUT")
  26. r.HandleFunc("/api/{group}/nodes/{macaddress}/checkin", authorize(true, "node", http.HandlerFunc(checkIn))).Methods("POST")
  27. r.HandleFunc("/api/{group}/nodes/{macaddress}/uncordon", authorize(true, "master", http.HandlerFunc(uncordonNode))).Methods("POST")
  28. r.HandleFunc("/api/{group}/nodes/{macaddress}", authorize(true, "node", http.HandlerFunc(deleteNode))).Methods("DELETE")
  29. r.HandleFunc("/api/{group}/authenticate", authenticate).Methods("POST")
  30. }
  31. //Node authenticates using its password and retrieves a JWT for authorization.
  32. func authenticate(response http.ResponseWriter, request *http.Request) {
  33. //Auth request consists of Mac Address and Password (from node that is authorizing
  34. //in case of Master, auth is ignored and mac is set to "mastermac"
  35. var authRequest models.AuthParams
  36. var result models.Node
  37. var errorResponse = models.ErrorResponse{
  38. Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
  39. }
  40. //Get password fnd mac rom request
  41. decoder := json.NewDecoder(request.Body)
  42. decoderErr := decoder.Decode(&authRequest)
  43. defer request.Body.Close()
  44. if decoderErr != nil {
  45. returnErrorResponse(response, request, errorResponse)
  46. return
  47. } else {
  48. errorResponse.Code = http.StatusBadRequest
  49. if authRequest.MacAddress == "" {
  50. errorResponse.Message = "W1R3: MacAddress can't be empty"
  51. returnErrorResponse(response, request, errorResponse)
  52. return
  53. } else if authRequest.Password == "" {
  54. errorResponse.Message = "W1R3: Password can't be empty"
  55. returnErrorResponse(response, request, errorResponse)
  56. return
  57. } else {
  58. //Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API untill approved).
  59. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  60. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  61. var err = collection.FindOne(ctx, bson.M{ "macaddress": authRequest.MacAddress, "ispending": false }).Decode(&result)
  62. defer cancel()
  63. if err != nil {
  64. returnErrorResponse(response, request, errorResponse)
  65. return
  66. }
  67. //compare password from request to stored password in database
  68. //might be able to have a common hash (certificates?) and compare those so that a password isn't passed in in plain text...
  69. //TODO: Consider a way of hashing the password client side before sending, or using certificates
  70. err = bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(authRequest.Password))
  71. if err != nil {
  72. returnErrorResponse(response, request, errorResponse)
  73. return
  74. } else {
  75. //Create a new JWT for the node
  76. tokenString, _ := functions.CreateJWT(authRequest.MacAddress, result.Group)
  77. if tokenString == "" {
  78. returnErrorResponse(response, request, errorResponse)
  79. return
  80. }
  81. var successResponse = models.SuccessResponse{
  82. Code: http.StatusOK,
  83. Message: "W1R3: Device " + authRequest.MacAddress + " Authorized",
  84. Response: models.SuccessfulLoginResponse{
  85. AuthToken: tokenString,
  86. MacAddress: authRequest.MacAddress,
  87. },
  88. }
  89. //Send back the JWT
  90. successJSONResponse, jsonError := json.Marshal(successResponse)
  91. if jsonError != nil {
  92. returnErrorResponse(response, request, errorResponse)
  93. return
  94. }
  95. response.Header().Set("Content-Type", "application/json")
  96. response.Write(successJSONResponse)
  97. }
  98. }
  99. }
  100. }
  101. //The middleware for most requests to the API
  102. //They all pass through here first
  103. //This will validate the JWT (or check for master token)
  104. //This will also check against the authGroup and make sure the node should be accessing that endpoint,
  105. //even if it's technically ok
  106. //This is kind of a poor man's RBAC. There's probably a better/smarter way.
  107. //TODO: Consider better RBAC implementations
  108. func authorize(groupCheck bool, authGroup string, next http.Handler) http.HandlerFunc {
  109. return func(w http.ResponseWriter, r *http.Request) {
  110. var errorResponse = models.ErrorResponse{
  111. Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
  112. }
  113. var params = mux.Vars(r)
  114. groupexists, _ := functions.GroupExists(params["group"])
  115. //check that the request is for a valid group
  116. //if (groupCheck && !groupexists) || err != nil {
  117. if (groupCheck && !groupexists) {
  118. errorResponse = models.ErrorResponse{
  119. Code: http.StatusNotFound, Message: "W1R3: This group does not exist. ",
  120. }
  121. returnErrorResponse(w, r, errorResponse)
  122. return
  123. } else {
  124. w.Header().Set("Content-Type", "application/json")
  125. //get the auth token
  126. bearerToken := r.Header.Get("Authorization")
  127. var tokenSplit = strings.Split(bearerToken, " ")
  128. //I put this in in case the user doesn't put in a token at all (in which case it's empty)
  129. //There's probably a smarter way of handling this.
  130. var authToken = "928rt238tghgwe@TY@$Y@#WQAEGB2FC#@HG#@$Hddd"
  131. if len(tokenSplit) > 1 {
  132. authToken = tokenSplit[1]
  133. } else {
  134. errorResponse = models.ErrorResponse{
  135. Code: http.StatusUnauthorized, Message: "W1R3: Missing Auth Token.",
  136. }
  137. returnErrorResponse(w, r, errorResponse)
  138. return
  139. }
  140. //This checks if
  141. //A: the token is the master password
  142. //B: the token corresponds to a mac address, and if so, which one
  143. //TODO: There's probably a better way of dealing with the "master token"/master password. Plz Halp.
  144. macaddress, _, err := functions.VerifyToken(authToken)
  145. if err != nil {
  146. errorResponse = models.ErrorResponse{
  147. Code: http.StatusUnauthorized, Message: "W1R3: Error Verifying Auth Token.",
  148. }
  149. returnErrorResponse(w, r, errorResponse)
  150. return
  151. }
  152. var isAuthorized = false
  153. //The mastermac (login with masterkey from config) can do everything!! May be dangerous.
  154. if macaddress == "mastermac" {
  155. isAuthorized = true
  156. //for everyone else, there's poor man's RBAC. The "cases" are defined in the routes in the handlers
  157. //So each route defines which access group should be allowed to access it
  158. } else {
  159. switch authGroup {
  160. case "all":
  161. isAuthorized = true
  162. case "nodes":
  163. isAuthorized = (macaddress != "")
  164. case "group":
  165. node, err := functions.GetNodeByMacAddress(params["group"], macaddress)
  166. if err != nil {
  167. errorResponse = models.ErrorResponse{
  168. Code: http.StatusUnauthorized, Message: "W1R3: Missing Auth Token.",
  169. }
  170. returnErrorResponse(w, r, errorResponse)
  171. return
  172. }
  173. isAuthorized = (node.Group == params["group"])
  174. case "node":
  175. isAuthorized = (macaddress == params["macaddress"])
  176. case "master":
  177. isAuthorized = (macaddress == "mastermac")
  178. default:
  179. isAuthorized = false
  180. }
  181. }
  182. if !isAuthorized {
  183. errorResponse = models.ErrorResponse{
  184. Code: http.StatusUnauthorized, Message: "W1R3: You are unauthorized to access this endpoint.",
  185. }
  186. returnErrorResponse(w, r, errorResponse)
  187. return
  188. } else {
  189. //If authorized, this function passes along it's request and output to the appropriate route function.
  190. next.ServeHTTP(w, r)
  191. }
  192. }
  193. }
  194. }
  195. //Returns a list of peers in "plaintext" format, which can be piped straight to a file (peers.conf) on a local machine
  196. //Not sure if it would be better to do that here or to let the client handle the formatting.
  197. //TODO: May want to consider a different approach
  198. func getPeerList(w http.ResponseWriter, r *http.Request) {
  199. w.Header().Set("Content-Type", "application/json")
  200. var nodes []models.Node
  201. var params = mux.Vars(r)
  202. //Connection mongoDB with mongoconn class
  203. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  204. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  205. //Get all nodes in the relevant group which are NOT in pending state
  206. filter := bson.M{"group": params["group"], "ispending": false}
  207. cur, err := collection.Find(ctx, filter)
  208. if err != nil {
  209. mongoconn.GetError(err, w)
  210. return
  211. }
  212. // Close the cursor once finished and cancel if it takes too long
  213. defer cancel()
  214. for cur.Next(context.TODO()) {
  215. var node models.Node
  216. err := cur.Decode(&node)
  217. if err != nil {
  218. log.Fatal(err)
  219. }
  220. // add the node to our node array
  221. //maybe better to just return this? But then that's just GetNodes...
  222. nodes = append(nodes, node)
  223. }
  224. //Uh oh, fatal error! This needs some better error handling
  225. //TODO: needs appropriate error handling so the server doesnt shut down.
  226. if err := cur.Err(); err != nil {
  227. log.Fatal(err)
  228. }
  229. //Writes output in the style familiar to WireGuard
  230. //Get's piped to peers.conf locally after client request
  231. for _, n := range nodes {
  232. w.Write([]byte("[Peer] \n"))
  233. w.Write([]byte("PublicKey = " + n.PublicKey + "\n"))
  234. w.Write([]byte("AllowedIPs = " + n.Address + "/32" + "\n"))
  235. w.Write([]byte("PersistentKeepalive = " + fmt.Sprint(n.PersistentKeepalive) + "\n"))
  236. w.Write([]byte("Endpoint = " + n.Endpoint + ":" + fmt.Sprint(n.ListenPort) + "\n\n"))
  237. }
  238. }
  239. //Gets all nodes associated with group, including pending nodes
  240. func getGroupNodes(w http.ResponseWriter, r *http.Request) {
  241. w.Header().Set("Content-Type", "application/json")
  242. var nodes []models.ReturnNode
  243. var params = mux.Vars(r)
  244. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  245. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  246. filter := bson.M{"group": params["group"]}
  247. //Filtering out the ID field cuz Dillon doesn't like it. May want to filter out other fields in the future
  248. cur, err := collection.Find(ctx, filter, options.Find().SetProjection(bson.M{"_id": 0}))
  249. if err != nil {
  250. mongoconn.GetError(err, w)
  251. return
  252. }
  253. defer cancel()
  254. for cur.Next(context.TODO()) {
  255. //Using a different model for the ReturnNode (other than regular node).
  256. //Either we should do this for ALL structs (so Groups and Keys)
  257. //OR we should just use the original struct
  258. //My preference is to make some new return structs
  259. //TODO: Think about this. Not an immediate concern. Just need to get some consistency eventually
  260. var node models.ReturnNode
  261. err := cur.Decode(&node)
  262. if err != nil {
  263. log.Fatal(err)
  264. }
  265. // add item our array of nodes
  266. nodes = append(nodes, node)
  267. }
  268. //TODO: Another fatal error we should take care of.
  269. if err := cur.Err(); err != nil {
  270. log.Fatal(err)
  271. }
  272. //Returns all the nodes in JSON format
  273. json.NewEncoder(w).Encode(nodes)
  274. }
  275. //A separate function to get all nodes, not just nodes for a particular group.
  276. //Not quite sure if this is necessary. Probably necessary based on front end but may want to review after iteration 1 if it's being used or not
  277. func getAllNodes(w http.ResponseWriter, r *http.Request) {
  278. w.Header().Set("Content-Type", "application/json")
  279. var nodes []models.ReturnNode
  280. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  281. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  282. // Filter out them ID's again
  283. cur, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"_id": 0}))
  284. if err != nil {
  285. mongoconn.GetError(err, w)
  286. return
  287. }
  288. defer cancel()
  289. for cur.Next(context.TODO()) {
  290. var node models.ReturnNode
  291. err := cur.Decode(&node)
  292. //TODO: Fatal error
  293. if err != nil {
  294. log.Fatal(err)
  295. }
  296. // add node to our array
  297. nodes = append(nodes, node)
  298. }
  299. //TODO: Fatal error
  300. if err := cur.Err(); err != nil {
  301. log.Fatal(err)
  302. }
  303. //Return all the nodes in JSON format
  304. json.NewEncoder(w).Encode(nodes)
  305. }
  306. //This function get's called when a node "checks in" at check in interval
  307. //Honestly I'm not sure what all it should be doing
  308. //TODO: Implement the necessary stuff, including the below
  309. //Check the last modified of the group
  310. //Check the last modified of the nodes
  311. //Write functions for responding to these two thingies
  312. func checkIn(w http.ResponseWriter, r *http.Request) {
  313. //TODO: Current thoughts:
  314. //Dont bother with a grouplastmodified
  315. //Instead, implement a "configupdate" boolean on nodes
  316. //when there is a group update that requrires a config update, then the node will pull its new config
  317. // set header.
  318. w.Header().Set("Content-Type", "application/json")
  319. var params = mux.Vars(r)
  320. var node models.Node
  321. //Retrieves node with DB Call which is inefficient. Let's just get the time and set it.
  322. //node = functions.GetNodeByMacAddress(params["group"], params["macaddress"])
  323. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  324. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  325. filter := bson.M{"macaddress": params["macaddress"]}
  326. //old code was inefficient, this is all we need.
  327. time := time.Now().String()
  328. //node.SetLastCheckIn()
  329. // prepare update model with new time
  330. update := bson.D{
  331. {"$set", bson.D{
  332. {"lastcheckin", time},
  333. }},
  334. }
  335. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&node)
  336. defer cancel()
  337. if errN != nil {
  338. mongoconn.GetError(errN, w)
  339. return
  340. }
  341. //TODO: check node last modified vs group last modified
  342. json.NewEncoder(w).Encode(node)
  343. }
  344. //Get an individual node. Nothin fancy here folks.
  345. func getNode(w http.ResponseWriter, r *http.Request) {
  346. // set header.
  347. w.Header().Set("Content-Type", "application/json")
  348. var params = mux.Vars(r)
  349. node, err := GetNode(params["macaddress"], params["group"])
  350. if err != nil {
  351. mongoconn.GetError(err, w)
  352. return
  353. }
  354. json.NewEncoder(w).Encode(node)
  355. }
  356. //Get the time that a group of nodes was last modified.
  357. //TODO: This needs to be refactored
  358. //Potential way to do this: On UpdateNode, set a new field for "LastModified"
  359. //If we go with the existing way, we need to at least set group.NodesLastModified on UpdateNode
  360. func getLastModified(w http.ResponseWriter, r *http.Request) {
  361. // set header.
  362. w.Header().Set("Content-Type", "application/json")
  363. var group models.Group
  364. var params = mux.Vars(r)
  365. collection := mongoconn.Client.Database("netmaker").Collection("groups")
  366. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  367. filter := bson.M{"nameid": params["group"]}
  368. err := collection.FindOne(ctx, filter).Decode(&group)
  369. defer cancel()
  370. if err != nil {
  371. fmt.Println(err)
  372. //log.Fatal(err)
  373. }
  374. w.Write([]byte(string(group.NodesLastModified)))
  375. }
  376. //This one's a doozy
  377. //To create a node
  378. //Must have valid key and be unique
  379. func createNode(w http.ResponseWriter, r *http.Request) {
  380. w.Header().Set("Content-Type", "application/json")
  381. var params = mux.Vars(r)
  382. var errorResponse = models.ErrorResponse{
  383. Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
  384. }
  385. groupName := params["group"]
  386. //Check if group exists first
  387. //TODO: This is inefficient. Let's find a better way.
  388. //Just a few rows down we grab the group anyway
  389. groupexists, errgroup := functions.GroupExists(groupName)
  390. if !groupexists || errgroup != nil {
  391. errorResponse = models.ErrorResponse{
  392. Code: http.StatusNotFound, Message: "W1R3: Group does not exist! ",
  393. }
  394. returnErrorResponse(w, r, errorResponse)
  395. return
  396. }
  397. var node models.Node
  398. //get node from body of request
  399. _ = json.NewDecoder(r.Body).Decode(&node)
  400. node.Group = groupName
  401. group, _ := node.GetGroup()
  402. //Check to see if key is valid
  403. //TODO: Triple inefficient!!! This is the third call to the DB we make for groups
  404. validKey := functions.IsKeyValid(groupName, node.AccessKey)
  405. if !validKey {
  406. //Check to see if group will allow manual sign up
  407. //may want to switch this up with the valid key check and avoid a DB call that way.
  408. if *group.AllowManualSignUp {
  409. node.IsPending = true
  410. } else {
  411. errorResponse = models.ErrorResponse{
  412. Code: http.StatusUnauthorized, Message: "W1R3: Key invalid, or none provided.",
  413. }
  414. returnErrorResponse(w, r, errorResponse)
  415. return
  416. }
  417. }
  418. err := ValidateNode("create", groupName, node)
  419. if err != nil {
  420. return
  421. }
  422. node, err = CreateNode(node, groupName)
  423. if err != nil {
  424. return
  425. }
  426. json.NewEncoder(w).Encode(node)
  427. }
  428. //Takes node out of pending state
  429. //TODO: May want to use cordon/uncordon terminology instead of "ispending".
  430. func uncordonNode(w http.ResponseWriter, r *http.Request) {
  431. w.Header().Set("Content-Type", "application/json")
  432. var params = mux.Vars(r)
  433. var node models.Node
  434. node, err := functions.GetNodeByMacAddress(params["group"], params["macaddress"])
  435. if err != nil {
  436. mongoconn.GetError(err, w)
  437. return
  438. }
  439. collection := mongoconn.Client.Database("netmaker").Collection("nodes")
  440. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  441. // Create filter
  442. filter := bson.M{"macaddress": params["macaddress"]}
  443. node.SetLastModified()
  444. fmt.Println("Uncordoning node " + node.Name)
  445. // prepare update model.
  446. update := bson.D{
  447. {"$set", bson.D{
  448. {"ispending", false},
  449. }},
  450. }
  451. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&node)
  452. defer cancel()
  453. if errN != nil {
  454. mongoconn.GetError(errN, w)
  455. return
  456. }
  457. fmt.Println("Node " + node.Name + " uncordoned.")
  458. json.NewEncoder(w).Encode("SUCCESS")
  459. }
  460. func updateNode(w http.ResponseWriter, r *http.Request) {
  461. w.Header().Set("Content-Type", "application/json")
  462. var params = mux.Vars(r)
  463. //Get id from parameters
  464. //id, _ := primitive.ObjectIDFromHex(params["id"])
  465. var node models.Node
  466. //start here
  467. node, err := functions.GetNodeByMacAddress(params["group"], params["macaddress"])
  468. if err != nil {
  469. json.NewEncoder(w).Encode(err)
  470. return
  471. }
  472. var nodechange models.Node
  473. // we decode our body request params
  474. _ = json.NewDecoder(r.Body).Decode(&nodechange)
  475. if nodechange.Group == "" {
  476. nodechange.Group = node.Group
  477. }
  478. if nodechange.MacAddress == "" {
  479. nodechange.MacAddress = node.MacAddress
  480. }
  481. err = ValidateNode("update", params["group"], nodechange)
  482. if err != nil {
  483. json.NewEncoder(w).Encode(err)
  484. return
  485. }
  486. node, err = UpdateNode(nodechange, node)
  487. if err != nil {
  488. json.NewEncoder(w).Encode(err)
  489. return
  490. }
  491. json.NewEncoder(w).Encode(node)
  492. }
  493. //Delete a node
  494. //Pretty straightforward
  495. func deleteNode(w http.ResponseWriter, r *http.Request) {
  496. // Set header
  497. w.Header().Set("Content-Type", "application/json")
  498. // get params
  499. var params = mux.Vars(r)
  500. success, err := DeleteNode(params["macaddress"], params["group"])
  501. if err != nil || !success {
  502. json.NewEncoder(w).Encode("Could not delete node " + params["macaddress"])
  503. return
  504. }
  505. json.NewEncoder(w).Encode(params["macaddress"] + " deleted.")
  506. }
  507. //A fun lil method for handling errors with http
  508. //Used in some cases but not others
  509. //1. This should probably be an application-wide function
  510. //2. All the API calls should probably be using this
  511. //3. The mongoconn should probably use this.
  512. //4. Need a consistent approach to error handling generally. Very haphazard at the moment
  513. //TODO: This is important. All Handlers should be replying with appropriate error code.
  514. func returnErrorResponse(response http.ResponseWriter, request *http.Request, errorMesage models.ErrorResponse) {
  515. httpResponse := &models.ErrorResponse{Code: errorMesage.Code, Message: errorMesage.Message}
  516. jsonResponse, err := json.Marshal(httpResponse)
  517. if err != nil {
  518. panic(err)
  519. }
  520. response.Header().Set("Content-Type", "application/json")
  521. response.WriteHeader(errorMesage.Code)
  522. response.Write(jsonResponse)
  523. }