Go web programming — parsing JSON requests and generating JSON responses

Time:2020-6-24

Now whether it’s a websiteApp, applet or mobileH5Page applications are deployed separately in front-end and back-endAPIIt is constructed in the form of interface interaction. Because it combines readability, encoded data size, and developer difficultyJSONFormat is a good choice, so the data format of the interface is usually adoptedJSON, that is, the front end is sendingPOSTPUTPATCHRequest to add, change the data toJSONFormat put to requestedBodyMedium. At the back end, all the data will beJSONFormat return.

aboutJSONReadability, encoded data size and developer’s difficulty in using, because its readability is not goodXMLStructure, but the amount of data is small, it is more convenient to operate with the program. contrastProtobufIn other words,ProtobufCoding speed, data size ratio after codingJSONIt’s all good, but it doesn’t work with the programJSONIt is convenient and simple. The encoded data is in binary format, and the readability is not at all. So on the wholeJSONIt’s a good idea in all aspects and it’s easy to be accepted by all people before it’s widely used (the above are all personal opinions).

I also wrote two articles about usingGoLanguage decoding and encodingJSONData articles

  • How to control the behavior of go encoding JSON data
  • Learn to use go to analyze complex JSON

So forWebProgramming, we just need to focus on how toHTTPRequestedBodyRead toJSONData, and how to return the data to the clientJSONFormat write toHTTPResponding.

Read JSON data from request body

This part of the content is actually mentioned in the previous article in-depth learning and parsing HTTP requests.

We need to treat the request body asjson.NewDecoder()The input stream of, and then theJSONFormat data parses into declared struct variables

//handler/parse_json_request
package handler

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

type Person struct {
    Name string
    Age  int
}

func DisplayPersonHandler(w http.ResponseWriter, r *http.Request) {
    var p Person

    //Parsing JSON data in the request body into the structure body
    //An error occurred, 400 error code returned
    err := json.NewDecoder(r.Body).Decode(&p)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    
    fmt.Fprintf(w, "Person: %+v", p)
}

// router/router.go
indexRouter.HandleFunc("/parse_json_request", handler.ParseJsonRequestHandler)

In the command linecURLCommand to test our program:

curl -X POST -d '{"name": "James", "age": 18}' \
     -H "Content-Type: application/json" \
     http://localhost:8000/index/parse_json_request

Write JSON data to response

In contrast to the above, data will be returned toJSONWhen the format is written to the response, we calljson.NewEncodeer(w).Encode(&v), using the response body as the input streamJSONEncoder, and then use itEncode()Method to code the data asJSONFormat and write the response body.

// handler/write_json_response
package handler

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

type User struct {
    FirstName string `json:"firstname"`
    LastName  string `json:"lastname"`
    Age       int    `json:"age"`
}

func WriteJsonResponseHandler(w http.ResponseWriter, r *http.Request) {
    p := User{
        FirstName: "John",
        LastName:  "Doe",
        Age:       25,
    }
  // Set response header
    w.Header().Set("Content-Type", "application/json")
    err := json.NewEncoder(w).Encode(&p)
    if err != nil {
        //... handle error
    }
}

// router/router.go
indexRouter.HandleFunc("/get_json_response", handler.WriteJsonResponseHandler)

After restarting the server, use thecURLCommand to test our program:

curl -X GET http://localhost:8000/index/get_json_response
{"firstname":"John","lastname":"Doe","age":25}

Today’s content is very simple. The source code has been uploaded. The official account has replied to gohttp12 to get the download link of the source code in the text.

Previous review

Learn to write HTTP server with go

Go web programming — Application ORM

Go web programming — Application guide of super detailed template library

Go web programming — using go language to create static file server

Go web programming — add error and access logs to your own servers

Go web programming -- parsing JSON requests and generating JSON responses

Recommended Today

Hot! Front and rear learning routes of GitHub target 144K

Hello, Sifu’s little friend. I’m silent Wang Er. Last week, while appreciating teacher Ruan Yifeng’s science and technology weekly, I found a powerful learning route, which has been marked with 144K on GitHub. It’s very popular. It covers not only the front-end and back-end learning routes, but also the operation and maintenance learning routes. As […]