登录
首页 >  Golang >  Go问答

使用 Golang 的 JSON 响应示例

来源:stackoverflow

时间:2024-04-05 12:00:38 223浏览 收藏

今天golang学习网给大家带来了《使用 Golang 的 JSON 响应示例》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~

问题内容

我正在尝试使用 golang 构建 api。首先,我只是在访问 http://localhost:8085/search 时尝试发送一些 json 数据,但我在浏览器中看到的只是 null

我从 medium 帖子中得到了这个示例

package main

import (
    "log"
    "net/http"
    "encoding/json"
    "github.com/gorilla/mux"
)

type Place struct {
  Location string `json:"123 Houston st"`
  Name string `json:"Ricks Barber Shop"`
  Body string `json:"this is the best barber shop in the world"`
}

var place []Place

func search(write http.ResponseWriter, req *http.Request) {
    write.Header().Set("Content-Type", "application/json")
    json.NewEncoder(write).Encode(place)
}

func main() {
    router := mux.NewRouter().StrictSlash(true)
    router.HandleFunc("/search", search).Methods("GET")
    log.Fatal(http.ListenAndServe(":8085", router))
}

解决方案


没有为您的“place”变量分配任何值。我想您正在尝试通过 json 标签分配值,但是此标签是为了通知 json 文件中的 json 属性的名称,而不是属性的值。

将您的代码调整为以下内容,它应该可以工作

type Place struct {
  Location string `json:"location"`
  Name string `json:"name"`
  Body string `json:"body"`
}

var place []Place

func search(write http.ResponseWriter, req *http.Request) {

  place = append(place, Place{Location: `123 Houston st`, Name:`Ricks Barber Shop`, Body:`this is the best barber shop in the world`})

   write.Header().Set("Content-Type", "application/json")
   j, err := json.Marshal(&place)

   if err != nil {
        //Your logic to handle Error
   }    

   fmt.Fprint(write, string(j)

}

Working command line program。您可以根据自己的需要进行调整。

https://play.golang.org/p/yHTcbqjoCjx

本篇关于《使用 Golang 的 JSON 响应示例》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>