Created
June 22, 2019 11:28
-
-
Save ripiuk/d1130f7648d5641e1b9b100d7b406049 to your computer and use it in GitHub Desktop.
Simple REST app using golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"github.com/gorilla/mux" | |
"log" | |
"math/rand" | |
"net/http" | |
"strconv" | |
) | |
type Book struct { | |
ID string `json:"id"` | |
Title string `json:"title"` | |
Author *Author `json:"author"` | |
} | |
type Author struct { | |
FirstName string `json:"first_name"` | |
LastName string `json:"last_name"` | |
} | |
var books []Book | |
func getBooks(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("Content-Type", "application/json") | |
json.NewEncoder(w).Encode(books) | |
} | |
func getBook(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("Content-Type", "application/json") | |
params := mux.Vars(r) | |
for _, item := range books { | |
if item.ID == params["id"] { | |
json.NewEncoder(w).Encode(item) | |
return | |
} | |
} | |
json.NewEncoder(w).Encode(&Book{}) | |
} | |
func createBook(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("Content-Type", "application/json") | |
var book Book | |
_ = json.NewDecoder(r.Body).Decode(&book) | |
book.ID = strconv.Itoa(rand.Intn(1000000)) | |
books = append(books, book) | |
json.NewEncoder(w).Encode(book) | |
} | |
func updateBook(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("Content-Type", "application/json") | |
params := mux.Vars(r) | |
for index, item := range books { | |
if item.ID == params["id"] { | |
books = append(books[:index], books[index+1:]...) | |
var book Book | |
_ = json.NewDecoder(r.Body).Decode(&book) | |
book.ID = params["id"] | |
books = append(books, book) | |
json.NewEncoder(w).Encode(book) | |
} | |
} | |
json.NewEncoder(w).Encode(books) | |
} | |
func deleteBook(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("Content-Type", "application/json") | |
params := mux.Vars(r) | |
for index, item := range books { | |
if item.ID == params["id"] { | |
books = append(books[:index], books[index+1:]...) | |
break | |
} | |
} | |
json.NewEncoder(w).Encode(books) | |
} | |
func main() { | |
r := mux.NewRouter() | |
books = append(books, Book{ID: "1", Title: "Человек в высоком замке", | |
Author: &Author{FirstName: "Филип", LastName: "Дик"}}) | |
r.HandleFunc("/books", getBooks).Methods("GET") | |
r.HandleFunc("/books/{id}", getBook).Methods("GET") | |
r.HandleFunc("/books", createBook).Methods("POST") | |
r.HandleFunc("/books/{id}", updateBook).Methods("PUT") | |
r.HandleFunc("/books/{id}", deleteBook).Methods("DELETE") | |
log.Fatal(http.ListenAndServe(":8000", r)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment