有人要求我使用Go做一个简单的RESTful服务,该服务必须使用其ID值检索有关特定书籍的所有数据。
public function index()
{
$users = User::all();
return view('users.profile')->with('users',$users);
}
public function show($id)
{
$users = User::find($id);
return view('users.profile')->with('users',$users);
}
预期输出 如果我输入-> http://localhost:8080/api/books/1 这一定要回报我
<h3>{{$users->name}}</h3>
相反,我的浏览器什么也没得到
答案 0 :(得分:0)
我只需按如下所示格式化代码,即可正常工作(请注意package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
type Book struct {
ID string `json:"id"`
Isbn string `json:"isbn"`
Title string `json:"title"`
Author *Author `json:"author"`
}
//Author struct
type Author struct {
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
}
//variables
//slice-> variable link to array
var books []Book
// Get single book
func getBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r) // Gets params
// Loop through books and find one with the id from the params
for _, item := range books {
if item.ID == params["id"] {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(item)
return
}
}
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(&Book{})
}
func main() {
fmt.Println("Listening on :8080")
// initialize mux router
r := mux.NewRouter()
// mock data
books = append(books, Book{ID: "1", Isbn: "32123", Title: "Book one", Author: &Author{Firstname: "J.K.", Lastname: "Rowling"}})
books = append(books, Book{ID: "2", Isbn: "45434", Title: "Book two", Author: &Author{Firstname: "P.K.", Lastname: "Rowling"}})
// router handler
r.HandleFunc("/api/books/{id}", getBook).Methods("GET")
log.Fatal(http.ListenAndServe(":8080", r))
}
函数)。
curl 127.0.0.1:8080/api/books/1
运行上述程序后。控制台上的以下命令:
{"id":"1","isbn":"32123","title":"Book one","author":{"firstname":"J.K.","lastname":"Rowling"}}
返回:
{{1}}
最后,作为使用Golang实现ReST API的建议,您可以选中here。