create a http server and read the request body as json and return a json response in go

main.go
package main

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

type RequestBody struct {
    Name string `json:"name"`
}

type ResponseBody struct {
    Message string `json:"message"`
}

func main() {
    http.HandleFunc("/hello", helloHandler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
    // read request body
    var reqBody RequestBody
    err := json.NewDecoder(r.Body).Decode(&reqBody)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    // create response body
    resBody := ResponseBody{
        Message: "Hello, " + reqBody.Name + "!",
    }

    // write response
    w.Header().Set("Content-Type", "application/json")
    err = json.NewEncoder(w).Encode(resBody)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
}
916 chars
44 lines

This program creates an HTTP server listening on port 8080. It handles requests to the /hello endpoint by reading the request body as JSON into a RequestBody struct, creating a ResponseBody struct with a simple greeting message, and returning the ResponseBody as JSON in the HTTP response. Any errors encountered during this process are handled and returned as appropriate HTTP status codes.

gistlibby LogSnag