douyou2234 2019-06-29 06:39
浏览 45

如何使用可用属性从json检索特定数据

I was asked to do a simple RESTful service using Go, that has to retrieve all the data about a particular book using its ID value.

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"] {
            json.NewEncoder(w).Encode(item)
            return
        }
    }
    json.NewEncoder(w).Encode(&Book{})
}

func main() {
    // r := mux.NewRouter()
    fmt.Println("hello api")
    //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",getBooks).Methods("GET")
    r.HandleFunc("/api/books/{id}",getBook).Methods("GET")
    r.HandleFunc("/api/books",createBook).Methods("POST")
    r.HandleFunc("/api/books/{id}",updateBook).Methods("PUT")
    r.HandleFunc("/api/books/{id}",deleteBook).Methods("DELETE")

    log.Fatal(http.ListenAndServe(":8080",r))    
}

expected output if i enter -> http://localhost:8080/api/books/1 this has to return me

{
    "id": "1",
    "isbn": "32123",
    "title": "Book one",
    "author": {
        "firstname": "J.K.",
        "lastname": "Rowling"
    }
}

instead, I'm getting nothing in my browser

  • 写回答

1条回答 默认 最新

  • doufubu2518 2019-06-29 08:16
    关注

    I just format the code as below and it works fine (pay attention to WriteHeader function).

    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))
    }
    

    After running the above program. The following command on the console:

    curl 127.0.0.1:8080/api/books/1
    

    returns:

    {"id":"1","isbn":"32123","title":"Book one","author":{"firstname":"J.K.","lastname":"Rowling"}}
    

    Finally, as a recommendation for implementing the ReST API with Golang, you can check here.

    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大