Skip to content

Instantly share code, notes, and snippets.

@IgnacioFan
Last active March 28, 2020 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IgnacioFan/2a60725d91fd2631f0448e0d5fa24db7 to your computer and use it in GitHub Desktop.
Save IgnacioFan/2a60725d91fd2631f0448e0d5fa24db7 to your computer and use it in GitHub Desktop.
package main
import(
"log"
"net/http"
"github.com/gorilla/mux"
)
func get(w http.ResponseWriter, r *http.Request){
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK) // set Status 200
w.Write([]byte(`{"message": "get called"}`))
}
func post(w http.ResponseWriter, r *http.Request){
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated) // set Status 201
w.Write([]byte(`{"message": "post called"}`))
}
func put(w http.ResponseWriter, r *http.Request){
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted) // set Status 202
w.Write([]byte(`{"message": "put called"}`))
}
func delete(w http.ResponseWriter, r *http.Request){
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"message": "delete called"}`))
}
func notFound(w http.ResponseWriter, r *http.Request){
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound) // set 404
w.Write([]byte(`{"message": "not found"}`))
}
func main() {
r := mux.NewRouter()
api := r.PathPrefix("/api/v1").Subrouter()
api.HandleFunc("/", get).Methods(http.MethodGet)
api.HandleFunc("/", post).Methods(http.MethodPost)
api.HandleFunc("/", put).Methods(http.MethodPut)
api.HandleFunc("/", delete).Methods(http.MethodDelete)
api.HandleFunc("/", notFound)
log.Fatal(http.ListenAndServe(":8000", r))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment