Go Server Response json

encoding/json

This package support byte(string) <-> struct conversion.

Next example shows how to create application/json response with encoding/json package.

Example

package main

import (
	"encoding/json"
	"net/http"
)

type APIResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
}

func jsonres(w http.ResponseWriter, r *http.Request) {
	response := new(APIResponse)
	response.Success = true
	response.Message = "Wow!"

	jsonBytes, err := json.Marshal(response)
	if err != nil {
		http.Error(w, "Json Error", 500)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.Write(jsonBytes)
}

func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.HandleFunc("/json", jsonres)
	server.ListenAndServe()
}

Test

Use “curl” command

curl localhost:8080/json   # {"success":true,"message":"Wow!"}
golang
スポンサーリンク
Professional Programmer2

コメント