-
Notifications
You must be signed in to change notification settings - Fork 12
REST API
Stephany Henrique Batista edited this page Jan 8, 2023
·
4 revisions
- Show how chi works and how install it Link
package main
import (
"net/http"
"github.com/go-chi/chi/v5"
)
func main() {
r := chi.NewRouter()
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, world 2!"))
})
http.ListenAndServe(":3000", r)
}- Show the differences between they
r.Get("/{param}", func(w http.ResponseWriter, r *http.Request) {
param := chi.URLParam(r, "param")
w.Write([]byte(param))
})
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
param := r.URL.Query().Get("param")
w.Write([]byte(param))
})- Install extension
- Make a script as example
GET http://localhost:3000/?param=testea- Explain what is payload
- GET does not have a body
r.Post("/campaign", func(w http.ResponseWriter, r *http.Request) {
var campaign campaign
err := render.DecodeJSON(r.Body, &campaign)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
campaign.Date = time.Now()
render.JSON(w, r, campaign)
})- Status code is a identifier of the http request where it can say if the resquest was ok or not.
- Code of 200 to 299 means that everything is ok
- Code of 400 to 499 means that is not ok and the request has a problem (something like data, securty or others)
- Code of 500 to 599 means that the server is crash
- What is http.handler and its interface
- what is http.handlerFunc and its code
- Why http.handler is not the default in our project
type myHandler struct {
message string
}
func (m *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(m.message))
}A good example of handlers is on link