Advertisement
Guest User

go.go

a guest
Jan 16th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 7.55 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "bufio"
  5.     "encoding/json"
  6.     "fmt"
  7.     "log"
  8.     "net/http"
  9.     "os"
  10.     "strconv"
  11.     "strings"
  12. )
  13.  
  14. type People struct {
  15.     Id   int
  16.     Name string
  17. }
  18.  
  19. type BaseModel interface {
  20.     create(string)
  21.     update(int, string)
  22.     find(int)
  23.     findAll()
  24.     last()
  25. }
  26.  
  27. type PeopleModel struct {
  28.     name string
  29. }
  30.  
  31. type PeopleModelTwo struct {
  32.     lastID int
  33.     data []People
  34. }
  35.  
  36. // implementing the interface for file as data source
  37.  
  38. func (c PeopleModel) create(name string) int {
  39.     f, err := os.OpenFile(c.name, os.O_APPEND|os.O_WRONLY, 0600)
  40.     defer f.Close()
  41.  
  42.     lastID := c.last()
  43.  
  44.     stringToWrite := ""
  45.  
  46.     if lastID == -1 {
  47.         stringToWrite = "1 " + name + "\n"
  48.     } else {
  49.         lastID = lastID + 1
  50.         stringToWrite = strconv.Itoa(lastID) + " " + name + "\n"
  51.     }
  52.     n, err := f.WriteString(stringToWrite)
  53.  
  54.     fmt.Println(n)
  55.  
  56.     if err != nil {
  57.         return 1
  58.     }
  59.     return -1
  60.  
  61. }
  62.  
  63. func (c PeopleModel) update(peopleID int, peopleName string) int {
  64.     allPeople := ""
  65.     found := false
  66.  
  67.     file, err := os.OpenFile(c.name, os.O_RDWR, 0644)
  68.     if err != nil {
  69.         log.Fatal(err)
  70.     }
  71.     defer file.Close()
  72.  
  73.     scanner := bufio.NewScanner(file)
  74.     for scanner.Scan() {
  75.         text := scanner.Text()
  76.         splittedText := strings.Split(text, " ")
  77.  
  78.         id := strings.Trim(splittedText[0], " ")
  79.         name := ""
  80.  
  81.         for index, element := range splittedText {
  82.             if index != 0 {
  83.                 name = name + element + " "
  84.             }
  85.         }
  86.  
  87.         intID, _ := strconv.Atoi(id)
  88.  
  89.         if intID == peopleID {
  90.             name = peopleName
  91.             found = true
  92.         }
  93.  
  94.         allPeople += id + " " + name + "\n"
  95.     }
  96.     file.WriteString(allPeople)
  97.     fmt.Println(allPeople)
  98.  
  99.     if err := scanner.Err(); err != nil {
  100.         log.Fatal(err)
  101.     }
  102.     if found {
  103.         return 1
  104.     }
  105.     return -1
  106. }
  107.  
  108. func (c PeopleModel) find(peopleID int) People {
  109.  
  110.     file, err := os.Open(c.name)
  111.     if err != nil {
  112.         log.Fatal(err)
  113.     }
  114.     defer file.Close()
  115.  
  116.     scanner := bufio.NewScanner(file)
  117.     for scanner.Scan() {
  118.         text := scanner.Text()
  119.         splittedText := strings.Split(text, " ")
  120.  
  121.         id := strings.Trim(splittedText[0], " ")
  122.         name := ""
  123.  
  124.         for index, element := range splittedText {
  125.             if index != 0 {
  126.                 name = name + element + " "
  127.             }
  128.         }
  129.  
  130.         intID, _ := strconv.Atoi(id)
  131.  
  132.         people := People{Id: intID, Name: name}
  133.  
  134.         if intID == peopleID {
  135.             return people
  136.         }
  137.  
  138.     }
  139.  
  140.     if err := scanner.Err(); err != nil {
  141.         log.Fatal(err)
  142.     }
  143.     peopleFake := People{Id: -1, Name: "shahin"} // doing very un idiomatic code here, cause i don't know how to handle it in go yet
  144.     return peopleFake
  145. }
  146.  
  147. func (c PeopleModel) findAll() []People {
  148.  
  149.     allPeople := []People{}
  150.  
  151.     file, err := os.Open(c.name)
  152.     if err != nil {
  153.         log.Fatal(err)
  154.     }
  155.     defer file.Close()
  156.  
  157.     scanner := bufio.NewScanner(file)
  158.     for scanner.Scan() {
  159.         text := scanner.Text()
  160.         splittedText := strings.Split(text, " ")
  161.  
  162.         id := strings.Trim(splittedText[0], " ")
  163.         name := ""
  164.  
  165.         for index, element := range splittedText {
  166.             if index != 0 {
  167.                 name = name + element + " "
  168.             }
  169.         }
  170.  
  171.         intID, _ := strconv.Atoi(id)
  172.  
  173.         fmt.Println(name)
  174.  
  175.         people := People{Id: intID, Name: name}
  176.  
  177.         allPeople = append(allPeople, people)
  178.  
  179.     }
  180.  
  181.     if err := scanner.Err(); err != nil {
  182.         log.Fatal(err)
  183.     }
  184.     return allPeople
  185. }
  186.  
  187. func (c PeopleModel) last() int {
  188.     file, err := os.Open(c.name)
  189.     if err != nil {
  190.         log.Fatal(err)
  191.     }
  192.     defer file.Close()
  193.  
  194.     lasttID := -1
  195.  
  196.     scanner := bufio.NewScanner(file)
  197.     for scanner.Scan() {
  198.         text := scanner.Text()
  199.         splittedText := strings.Split(text, " ")
  200.  
  201.         id := strings.Trim(splittedText[0], " ")
  202.         name := ""
  203.  
  204.         for index, element := range splittedText {
  205.             if index != 0 {
  206.                 name = name + element + " "
  207.             }
  208.         }
  209.  
  210.         intID, _ := strconv.Atoi(id)
  211.         lasttID = intID
  212.     }
  213.  
  214.     if err := scanner.Err(); err != nil {
  215.         log.Fatal(err)
  216.     }
  217.     return lasttID
  218. }
  219.  
  220. // implementing the interface for in memory
  221. func (c *PeopleModelTwo) create(name string) int {
  222.     people := People{Id: c.lastID, Name: name}
  223.     c.lastID = c.lastID + 1
  224.     c.data = append(c.data, people)
  225.     fmt.Println(c)
  226.     return -1
  227. }
  228.  
  229. func (c *PeopleModelTwo) update(peopleID int, peopleName string) int {
  230.     found := false
  231.     for _,v  := range c.data {
  232.         if v.Id == peopleID {
  233.             v.Name = peopleName
  234.             found = true
  235.         }
  236.     }
  237.  
  238.     if found {
  239.         return 1
  240.     }
  241.    
  242.     return -1
  243. }
  244.  
  245. func (c *PeopleModelTwo) find(peopleID int) People {
  246.     for _,v  := range c.data {
  247.         if v.Id == peopleID {
  248.             return v
  249.         }
  250.     }
  251.     peopleFake := People{Id: -1, Name: "shahin"} // doing very un idiomatic code here, cause i don't know how to handle it in go yet
  252.     return peopleFake
  253. }
  254.  
  255. func (c *PeopleModelTwo) findAll() []People {
  256.     fmt.Println(c)
  257.     return c.data
  258. }
  259.  
  260. func (c *PeopleModelTwo) last() int {
  261.     return -1
  262. }
  263.  
  264.  
  265. func main() {
  266.  
  267.     // these are configuration file
  268.     // our data model would resolve here for now
  269.     //filePath := "././model/people.txt"
  270.     //dataModel := PeopleModel{name: filePath}
  271.    
  272.     dataModel :=  new(PeopleModelTwo)
  273.     dataModel.lastID = 0
  274.    
  275.  
  276.     // test endpoint
  277.     http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
  278.  
  279.         m := map[string]string{"message": "Hurray, the test endpoint is working."}
  280.  
  281.         data, err := json.Marshal(m)
  282.         if err != nil {
  283.             w.Write([]byte("something went wrong"))
  284.         }
  285.  
  286.         w.Header().Set("Content-Type", "application/json")
  287.  
  288.         w.Write(data)
  289.  
  290.     })
  291.  
  292.     // all people get endpoing
  293.     http.HandleFunc("/all-people", func(w http.ResponseWriter, r *http.Request) {
  294.         responseString := dataModel.findAll()
  295.         responseJSON, _ := json.Marshal(responseString)
  296.         fmt.Println(responseString)
  297.         w.Write(responseJSON)
  298.     })
  299.  
  300.     // single people get endpoing
  301.     http.HandleFunc("/people", func(w http.ResponseWriter, r *http.Request) {
  302.         id := r.URL.Query().Get("id")
  303.  
  304.         intID, err := strconv.Atoi(id)
  305.  
  306.         if err != nil {
  307.             m := map[string]string{"message": "Invalid user ID"}
  308.             data, _ := json.Marshal(m)
  309.             w.Header().Set("Content-Type", "application/json")
  310.  
  311.             w.Write(data)
  312.  
  313.         }
  314.  
  315.         data := dataModel.find(intID)
  316.         if data.Id == -1 {
  317.             m := map[string]string{"message": "User Not Found"}
  318.             data, _ := json.Marshal(m)
  319.             w.Header().Set("Content-Type", "application/json")
  320.             w.Write(data)
  321.         } else {
  322.             dataFinal, _ := json.Marshal(data)
  323.             w.Header().Set("Content-Type", "application/json")
  324.             w.Write(dataFinal)
  325.         }
  326.  
  327.     })
  328.  
  329.     // single people post update endpoing
  330.     http.HandleFunc("/people/update", func(w http.ResponseWriter, r *http.Request) {
  331.  
  332.         id := r.URL.Query().Get("id")
  333.         name := r.FormValue("name")
  334.  
  335.         intID, err := strconv.Atoi(id)
  336.  
  337.         if err != nil {
  338.             m := map[string]string{"message": "Invalid user ID"}
  339.             data, _ := json.Marshal(m)
  340.             w.Header().Set("Content-Type", "application/json")
  341.  
  342.             w.Write(data)
  343.  
  344.         }
  345.  
  346.         data := dataModel.update(intID, name)
  347.         if data == -1 {
  348.             m := map[string]string{"message": "User Not Found"}
  349.             data, _ := json.Marshal(m)
  350.             w.Header().Set("Content-Type", "application/json")
  351.             w.Write(data)
  352.         } else {
  353.             m := map[string]string{"message": "User Updated Successfully"}
  354.             data, _ := json.Marshal(m)
  355.             w.Header().Set("Content-Type", "application/json")
  356.             w.Write(data)
  357.         }
  358.  
  359.     })
  360.  
  361.     // new people post endpoint
  362.     http.HandleFunc("/new-people", func(w http.ResponseWriter, r *http.Request) {
  363.  
  364.         name := r.FormValue("name")
  365.  
  366.         status := dataModel.create(name)
  367.  
  368.         m := map[string]string{}
  369.  
  370.         if status == -1 {
  371.             m = map[string]string{"message": "Successfull."}
  372.  
  373.         } else {
  374.             m = map[string]string{"message": "Sorry. It failed"}
  375.         }
  376.  
  377.         data, _ := json.Marshal(m)
  378.  
  379.         w.Header().Set("Content-Type", "application/json")
  380.  
  381.         w.Write(data)
  382.  
  383.     })
  384.  
  385.     // listening on 8080
  386.     log.Fatal(http.ListenAndServe(":3001", nil))
  387.  
  388. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement