ZhangZhihui's Blog  

Problem: You want to create a simple web service API that returns JSON.


Solution: Use the net/http package to create a web service API and the encoding/json package to encode data to be sent back as JSON.

 

You’ll create a web service API that returns a list of people in JSON format. You’ll use the net/http and chi packages to create the web service API and the encoding/json package to encode data to be sent back as JSON. 

Start by creating a Person struct:

复制代码
type Person struct {
    Name      string `json:"name"`
    Height    string `json:"height"`
    Mass      string `json:"mass"`
    HairColor string `json:"hair_color"`
    SkinColor string `json:"skin_color"`
    EyeColor  string `json:"eye_color"`
    BirthYear string `json:"birth_year"`
    Gender    string `json:"gender"`
}

var list []Person

func init() {
    file, _ := os.Open("./datafiles/people.json")
    defer file.Close()
    data, _ := io.ReadAll(file)
    json.Unmarshal(data, &list)
}
复制代码

You use the init function to initialize the list variable with the data from the people.json file. This will be the data that you’ll return as JSON:

复制代码
[ 
      { 
      "name" :   "Luke  Skywalker" , 
      "height" :   "172" , 
      "mass" :   "77" , 
      "hair_color" :   "blond" , 
      "skin_color" :   "fair" , 
      "eye_color" :   "blue" , 
      "birth_year" :   "19BBY" , 
      "gender" :   "male" 
      }, 
      { 
      "name" :   "C - 3PO" , 
      "height" :   "167" , 
      "mass" :   "75" , 
      "hair_color" :   "n/a" , 
      "skin_color" :   "gold" , 
      "eye_color" :   "yellow" , 
      "birth_year" :   "112BBY" , 
      "gender" :   "n/a" 
      }, 
      { 
      "name" :   "R2 - D2" , 
      "height" :   "96" , 
      "mass" :   "32" , 
      "hair_color" :   "n/a" , 
      "skin_color" :   "white,  blue" , 
      "eye_color" :   "red" , 
      "birth_year" :   "33BBY" , 
      "gender" :   "n/a" 
      } 
]
复制代码

Now you create a handler that uses the pattern "/people/{id}" to create a RESTful API that uses the path pattern /people/<id> :

复制代码
func main() {
    mux := chi.NewRouter()
    mux.Get("/people/{id}", people)
    http.ListenAndServe(":8000", mux)
}

func people(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    idstr := chi.URLParam(r, "id") // r.PathValue("id")
    id, err := strconv.Atoi(idstr)
    if err != nil {
        w.WriteHeader(http.StatusBadRequest)
        return
    }
    if id < 0 || id >= len(list) {
        w.WriteHeader(http.StatusNotFound)
        return
    }
    json.NewEncoder(w).Encode(list[id])
}
复制代码

First, set the Content-Type header to application/json . This tells the client that the response is in JSON format. Next, get the id from the URL path using the chi.URLParam function. If the id is not a number, you return a 400 Bad Request error. If the id is out of range, you return a 404 Not Found error.

 

posted on   ZhangZhihuiAAA  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2019-10-17 PyCharm - disable autosave
 
点击右上角即可分享
微信分享提示