我是从获取数据github API有golang,但是,我要发送到前只将必要的数据(id,name,url,language和description的),而不是仅仅返回所有的github API给我。
func GetAllReposStars(w http.ResponseWriter, r *http.Request) {
enableCors(&w)
params := mux.Vars(r)
username := params["username"]
res, err := http.Get("https://api.github.com/users/" + username + "/starred")
body, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
}
log.Printf("Body: %s\n", body)
if err != nil {
log.Fatal(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(body)
json.NewEncoder(w)
}
Run Code Online (Sandbox Code Playgroud)
您可以定义一个只有您需要的密钥的类型,并将来自 GitHub API 的响应解码为该类型的变量,以便只保留您需要的密钥,然后将该变量写入响应。
例如:
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
type RelevantRepoData struct {
Id int `json:"id"`
Name string `json:"name"`
Url string `json:"url"`
Language string `json:"language"`
Description string `json:"description"`
}
func GetAllReposStars(w http.ResponseWriter, r *http.Request) {
enableCors(&w)
params := mux.Vars(r)
username := params["username"]
res, err := http.Get("https://api.github.com/users/" + username + "/starred")
var repoData RelevantRepoData
err = json.NewDecoder(res.Body).Decode(&repoData)
if err != nil {
log.Fatal(err)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(repoData)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |