return a json response from a http server with a specific status code in go

You can use the net/http package to create a HTTP server in Go. Here's an example of how to return a JSON response with a specific status code:

main.go
package main

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

type Person struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}

func main() {
    // Define a handler function for the HTTP request
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // Create a new Person object
        person := Person{"Jane Doe", "jane.doe@example.com"}

        // Convert the Person object to a JSON byte array
        jsonBytes, err := json.Marshal(person)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }

        // Set the Content-Type header to application/json
        w.Header().Set("Content-Type", "application/json")

        // Write the JSON byte array to the response
        w.WriteHeader(http.StatusOK)
        w.Write(jsonBytes)
    })

    // Start the HTTP server on port 8080
    http.ListenAndServe(":8080", nil)
}
944 chars
37 lines

In this example, we define a handler function that creates a Person object, converts it to a JSON byte array using json.Marshal, sets the Content-Type header to application/json, writes the JSON byte array to the response using w.Write, and sets the status code using w.WriteHeader. The http.Error function is used to return a 500 Internal Server Error status code if there was an error converting the Person object to JSON.

related categories

gistlibby LogSnag