start using Marshal for creating json responses
This commit is contained in:
parent
38deaabd49
commit
147bbb3e81
|
@ -1,13 +1,30 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (app *application) healthCheckHandler(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintln(w, "status: available")
|
||||
fmt.Fprintf(w, "environment: %s\n", app.config.env)
|
||||
fmt.Fprintf(w, "version: %s", version)
|
||||
|
||||
// create a mapping that will be converted to json
|
||||
data := map[string]string{
|
||||
"status": "available",
|
||||
"environment": app.config.env,
|
||||
"version": version,
|
||||
}
|
||||
|
||||
js, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
app.logger.Print(err)
|
||||
http.Error(w, "the server encountered an error and could process your request", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
js = append(js, '\n')
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
w.Write(js)
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,20 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
)
|
||||
|
||||
func (app *application) readIDParam(r *http.Request) (int64, error) {
|
||||
params := httprouter.ParamsFromContext(r.Context())
|
||||
|
||||
id, err := strconv.ParseInt(params.ByName("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
return 0, errors.New("invalid id parameter")
|
||||
}
|
||||
|
||||
return id, nil
|
||||
}
|
|
@ -3,9 +3,6 @@ package main
|
|||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
)
|
||||
|
||||
func (app *application) createMovieHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
@ -13,9 +10,7 @@ func (app *application) createMovieHandler(w http.ResponseWriter, r *http.Reques
|
|||
}
|
||||
|
||||
func (app *application) showMovieHandler(w http.ResponseWriter, r *http.Request) {
|
||||
params := httprouter.ParamsFromContext(r.Context())
|
||||
|
||||
id, err := strconv.ParseInt(params.ByName("id"), 10, 64)
|
||||
id, err := app.readIDParam(r)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
|
|
Loading…
Reference in New Issue