Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "bufio"
- "encoding/json"
- "fmt"
- "log"
- "net/http"
- "os"
- "strconv"
- "strings"
- )
- type People struct {
- Id int
- Name string
- }
- type BaseModel interface {
- create(string)
- update(int, string)
- find(int)
- findAll()
- last()
- }
- type PeopleModel struct {
- name string
- }
- type PeopleModelTwo struct {
- lastID int
- data []People
- }
- // implementing the interface for file as data source
- func (c PeopleModel) create(name string) int {
- f, err := os.OpenFile(c.name, os.O_APPEND|os.O_WRONLY, 0600)
- defer f.Close()
- lastID := c.last()
- stringToWrite := ""
- if lastID == -1 {
- stringToWrite = "1 " + name + "\n"
- } else {
- lastID = lastID + 1
- stringToWrite = strconv.Itoa(lastID) + " " + name + "\n"
- }
- n, err := f.WriteString(stringToWrite)
- fmt.Println(n)
- if err != nil {
- return 1
- }
- return -1
- }
- func (c PeopleModel) update(peopleID int, peopleName string) int {
- allPeople := ""
- found := false
- file, err := os.OpenFile(c.name, os.O_RDWR, 0644)
- if err != nil {
- log.Fatal(err)
- }
- defer file.Close()
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- text := scanner.Text()
- splittedText := strings.Split(text, " ")
- id := strings.Trim(splittedText[0], " ")
- name := ""
- for index, element := range splittedText {
- if index != 0 {
- name = name + element + " "
- }
- }
- intID, _ := strconv.Atoi(id)
- if intID == peopleID {
- name = peopleName
- found = true
- }
- allPeople += id + " " + name + "\n"
- }
- file.WriteString(allPeople)
- fmt.Println(allPeople)
- if err := scanner.Err(); err != nil {
- log.Fatal(err)
- }
- if found {
- return 1
- }
- return -1
- }
- func (c PeopleModel) find(peopleID int) People {
- file, err := os.Open(c.name)
- if err != nil {
- log.Fatal(err)
- }
- defer file.Close()
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- text := scanner.Text()
- splittedText := strings.Split(text, " ")
- id := strings.Trim(splittedText[0], " ")
- name := ""
- for index, element := range splittedText {
- if index != 0 {
- name = name + element + " "
- }
- }
- intID, _ := strconv.Atoi(id)
- people := People{Id: intID, Name: name}
- if intID == peopleID {
- return people
- }
- }
- if err := scanner.Err(); err != nil {
- log.Fatal(err)
- }
- peopleFake := People{Id: -1, Name: "shahin"} // doing very un idiomatic code here, cause i don't know how to handle it in go yet
- return peopleFake
- }
- func (c PeopleModel) findAll() []People {
- allPeople := []People{}
- file, err := os.Open(c.name)
- if err != nil {
- log.Fatal(err)
- }
- defer file.Close()
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- text := scanner.Text()
- splittedText := strings.Split(text, " ")
- id := strings.Trim(splittedText[0], " ")
- name := ""
- for index, element := range splittedText {
- if index != 0 {
- name = name + element + " "
- }
- }
- intID, _ := strconv.Atoi(id)
- fmt.Println(name)
- people := People{Id: intID, Name: name}
- allPeople = append(allPeople, people)
- }
- if err := scanner.Err(); err != nil {
- log.Fatal(err)
- }
- return allPeople
- }
- func (c PeopleModel) last() int {
- file, err := os.Open(c.name)
- if err != nil {
- log.Fatal(err)
- }
- defer file.Close()
- lasttID := -1
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- text := scanner.Text()
- splittedText := strings.Split(text, " ")
- id := strings.Trim(splittedText[0], " ")
- name := ""
- for index, element := range splittedText {
- if index != 0 {
- name = name + element + " "
- }
- }
- intID, _ := strconv.Atoi(id)
- lasttID = intID
- }
- if err := scanner.Err(); err != nil {
- log.Fatal(err)
- }
- return lasttID
- }
- // implementing the interface for in memory
- func (c *PeopleModelTwo) create(name string) int {
- people := People{Id: c.lastID, Name: name}
- c.lastID = c.lastID + 1
- c.data = append(c.data, people)
- fmt.Println(c)
- return -1
- }
- func (c *PeopleModelTwo) update(peopleID int, peopleName string) int {
- found := false
- for _,v := range c.data {
- if v.Id == peopleID {
- v.Name = peopleName
- found = true
- }
- }
- if found {
- return 1
- }
- return -1
- }
- func (c *PeopleModelTwo) find(peopleID int) People {
- for _,v := range c.data {
- if v.Id == peopleID {
- return v
- }
- }
- peopleFake := People{Id: -1, Name: "shahin"} // doing very un idiomatic code here, cause i don't know how to handle it in go yet
- return peopleFake
- }
- func (c *PeopleModelTwo) findAll() []People {
- fmt.Println(c)
- return c.data
- }
- func (c *PeopleModelTwo) last() int {
- return -1
- }
- func main() {
- // these are configuration file
- // our data model would resolve here for now
- //filePath := "././model/people.txt"
- //dataModel := PeopleModel{name: filePath}
- dataModel := new(PeopleModelTwo)
- dataModel.lastID = 0
- // test endpoint
- http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
- m := map[string]string{"message": "Hurray, the test endpoint is working."}
- data, err := json.Marshal(m)
- if err != nil {
- w.Write([]byte("something went wrong"))
- }
- w.Header().Set("Content-Type", "application/json")
- w.Write(data)
- })
- // all people get endpoing
- http.HandleFunc("/all-people", func(w http.ResponseWriter, r *http.Request) {
- responseString := dataModel.findAll()
- responseJSON, _ := json.Marshal(responseString)
- fmt.Println(responseString)
- w.Write(responseJSON)
- })
- // single people get endpoing
- http.HandleFunc("/people", func(w http.ResponseWriter, r *http.Request) {
- id := r.URL.Query().Get("id")
- intID, err := strconv.Atoi(id)
- if err != nil {
- m := map[string]string{"message": "Invalid user ID"}
- data, _ := json.Marshal(m)
- w.Header().Set("Content-Type", "application/json")
- w.Write(data)
- }
- data := dataModel.find(intID)
- if data.Id == -1 {
- m := map[string]string{"message": "User Not Found"}
- data, _ := json.Marshal(m)
- w.Header().Set("Content-Type", "application/json")
- w.Write(data)
- } else {
- dataFinal, _ := json.Marshal(data)
- w.Header().Set("Content-Type", "application/json")
- w.Write(dataFinal)
- }
- })
- // single people post update endpoing
- http.HandleFunc("/people/update", func(w http.ResponseWriter, r *http.Request) {
- id := r.URL.Query().Get("id")
- name := r.FormValue("name")
- intID, err := strconv.Atoi(id)
- if err != nil {
- m := map[string]string{"message": "Invalid user ID"}
- data, _ := json.Marshal(m)
- w.Header().Set("Content-Type", "application/json")
- w.Write(data)
- }
- data := dataModel.update(intID, name)
- if data == -1 {
- m := map[string]string{"message": "User Not Found"}
- data, _ := json.Marshal(m)
- w.Header().Set("Content-Type", "application/json")
- w.Write(data)
- } else {
- m := map[string]string{"message": "User Updated Successfully"}
- data, _ := json.Marshal(m)
- w.Header().Set("Content-Type", "application/json")
- w.Write(data)
- }
- })
- // new people post endpoint
- http.HandleFunc("/new-people", func(w http.ResponseWriter, r *http.Request) {
- name := r.FormValue("name")
- status := dataModel.create(name)
- m := map[string]string{}
- if status == -1 {
- m = map[string]string{"message": "Successfull."}
- } else {
- m = map[string]string{"message": "Sorry. It failed"}
- }
- data, _ := json.Marshal(m)
- w.Header().Set("Content-Type", "application/json")
- w.Write(data)
- })
- // listening on 8080
- log.Fatal(http.ListenAndServe(":3001", nil))
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement