packagemainimport("log""net/http""encoding/json""github.com/gorilla/mux")funcmain(){router:=mux.NewRouter()router.HandleFunc("/books",func(whttp.ResponseWriter,r*http.Request){json.NewEncoder(w).Encode("Hello World")})log.Println("API is running!")http.ListenAndServe(":4000",router)}
packagemainimport("log""net/http""github.com/gorilla/mux""github.com/karanpratapsingh/tutorials/go/crud/pkg/handlers")funcmain(){router:=mux.NewRouter()// Here we'll define our api endpointslog.Println("API is running!")http.ListenAndServe(":4000",router)}
packagemocksimport"github.com/karanpratapsingh/tutorials/go/crud/pkg/models"varBooks=[]models.Book{{Id:1,Title:"Golang",Author:"Gopher",Desc:"A book for Go",},}
packagehandlersimport("encoding/json""io/ioutil""log""math/rand""net/http""github.com/karanpratapsingh/tutorials/go/crud/pkg/mocks""github.com/karanpratapsingh/tutorials/go/crud/pkg/models")funcAddBook(whttp.ResponseWriter,r*http.Request){// Read to request bodydeferr.Body.Close()body,err:=ioutil.ReadAll(r.Body)iferr!=nil{log.Fatalln(err)}varbookmodels.Bookjson.Unmarshal(body,&book)// Append to the Book mocksbook.Id=rand.Intn(100)mocks.Books=append(mocks.Books,book)// Send a 201 created responsew.Header().Add("Content-Type","application/json")w.WriteHeader(http.StatusCreated)json.NewEncoder(w).Encode("Created")}
packagehandlersimport("encoding/json""net/http""strconv""github.com/gorilla/mux""github.com/karanpratapsingh/tutorials/go/crud/pkg/mocks")funcGetBook(whttp.ResponseWriter,r*http.Request){// Read dynamic id parametervars:=mux.Vars(r)id,_:=strconv.Atoi(vars["id"])// Iterate over all the mock booksfor_,book:=rangemocks.Books{ifbook.Id==id{// If ids are equal send book as a responsew.Header().Add("Content-Type","application/json")w.WriteHeader(http.StatusOK)json.NewEncoder(w).Encode(book)break}}}
packagehandlersimport("encoding/json""io/ioutil""log""net/http""strconv""github.com/gorilla/mux""github.com/karanpratapsingh/tutorials/go/crud/pkg/mocks""github.com/karanpratapsingh/tutorials/go/crud/pkg/models")funcUpdateBook(whttp.ResponseWriter,r*http.Request){// Read dynamic id parametervars:=mux.Vars(r)id,_:=strconv.Atoi(vars["id"])// Read request bodydeferr.Body.Close()body,err:=ioutil.ReadAll(r.Body)iferr!=nil{log.Fatalln(err)}varupdatedBookmodels.Bookjson.Unmarshal(body,&updatedBook)// Iterate over all the mock Booksforindex,book:=rangemocks.Books{ifbook.Id==id{// Update and send a response when book Id matches dynamic Idbook.Title=updatedBook.Titlebook.Author=updatedBook.Authorbook.Desc=updatedBook.Descmocks.Books[index]=bookw.Header().Add("Content-Type","application/json")w.WriteHeader(http.StatusOK)json.NewEncoder(w).Encode("Updated")break}}}
packagehandlersimport("encoding/json""net/http""strconv""github.com/gorilla/mux""github.com/karanpratapsingh/tutorials/go/crud/pkg/mocks")funcDeleteBook(whttp.ResponseWriter,r*http.Request){// Read the dynamic id parametervars:=mux.Vars(r)id,_:=strconv.Atoi(vars["id"])// Iterate over all the mock Booksforindex,book:=rangemocks.Books{ifbook.Id==id{// Delete book and send a response if the book Id matches dynamic Idmocks.Books=append(mocks.Books[:index],mocks.Books[index+1:]...)w.Header().Add("Content-Type","application/json")w.WriteHeader(http.StatusOK)json.NewEncoder(w).Encode("Deleted")break}}}
让我们启动服务器并在 Postman 中尝试一下
$ go run cmd/main.go
后续步骤Next steps
好了,我们用 Go 构建了一个基本的 CRUD API!下一步可能是将我们的 API 与像 PostgreSQL 这样的真正数据库连接起来,我们将在下一部分中详细探讨!