简体   繁体   中英

Example JSON response with Golang

I am trying to build an API with golang. To get started I am just trying to send some json data when I visit http://localhost:8085/search but all I am viewing in the browser is null .

I got this example from a Medium post

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

There's no value assigned to your "place" variable. I suppose you're trying to assign values through the json tags, however this tag is to inform the name of the json property within the json file and not the value of the property.

Adapt your code to the below and it should work

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 . You can adapt this to your needs.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM