Advertisement
Guest User

http

a guest
Jun 21st, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.81 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "encoding/json"
  5.     "fmt"
  6.     "net/http"
  7. )
  8.  
  9. type Note struct {
  10.     Id         string `json:"id"`
  11.     Title      string `json:"title"`
  12.     Text       string `json:"text"`
  13.     DateCreate uint   `json:"date_create"`
  14.     DateUpdate uint   `json:"date_update"`
  15. }
  16.  
  17. var preparedNotes = []Note{
  18.     Note{"10dcdccb-8876-4245-ac53-92900c6509bd", "Первая заметка", "Вторая заметка", 1513759529, 1517259529},
  19.     Note{"10dcdccb-8876-4245-ac53-92900c6509bd", "Первая заметка", "Вторая заметка", 1513759529, 1517259529},
  20. }
  21.  
  22. func addNote(w http.ResponseWriter, r *http.Request) {
  23.     var note Note
  24.     err := json.NewDecoder(r.Body).Decode(&note)
  25.     if err != nil || note.Text == "" || note.Title == "" {
  26.         w.WriteHeader(400)
  27.         return
  28.     }
  29.  
  30.     //add
  31.  
  32.     w.WriteHeader(201)
  33. }
  34.  
  35. func updateNote(w http.ResponseWriter, r *http.Request) {
  36.     var note Note
  37.     err := json.NewDecoder(r.Body).Decode(&note)
  38.     if err != nil || note.Id == "" || note.Text == "" || note.Title == "" {
  39.         w.WriteHeader(400)
  40.         return
  41.     }
  42.  
  43.     //update
  44.  
  45.     w.WriteHeader(201)
  46. }
  47.  
  48. func deleteNote(w http.ResponseWriter, r *http.Request) {
  49.     var note Note
  50.     err := json.NewDecoder(r.Body).Decode(&note)
  51.     if err != nil || note.Id == "" {
  52.         w.WriteHeader(400)
  53.         return
  54.     }
  55.  
  56.     //delete
  57.  
  58.     w.WriteHeader(204)
  59. }
  60.  
  61. func getNotes(w http.ResponseWriter, r *http.Request) {
  62.     w.Header().Set("Content-type", "application/json; charset=utf-8")
  63.     if err := json.NewEncoder(w).Encode(preparedNotes); err != nil {
  64.         w.WriteHeader(500)
  65.     }
  66. }
  67.  
  68. func updateRecord(w http.ResponseWriter, r *http.Request) {
  69.  
  70. }
  71.  
  72. func main() {
  73.  
  74.     //http.HandleFunc("")
  75.     http.MethodDelete("/", deleteNote)
  76.     http.HandleFunc("/", getNotes)
  77.     http.HandleFunc("/", addNote)
  78.     fmt.Println("Starting server at 8080")
  79.     http.ListenAndServe(":8080", nil)
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement