Skip to content

Instantly share code, notes, and snippets.

@mageddo
Created August 26, 2017 21:38
Show Gist options
  • Select an option

  • Save mageddo/a7dda72895ae1c10706f794cbe3d766d to your computer and use it in GitHub Desktop.

Select an option

Save mageddo/a7dda72895ae1c10706f794cbe3d766d to your computer and use it in GitHub Desktop.
package controller
func init(){
Get("/", func(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "%s", "Hi!")
})
}
package controller
import (
"net/http"
"encoding/json"
"github.com/mageddo/go-logging"
"context"
"github.com/mageddo/bookmark-notes/log"
)
type Method string
const (
POST Method = "POST"
GET Method = "GET"
PUT Method = "PUT"
PATCH Method = "PATCH"
DELETE Method = "DELETE"
)
type Message struct {
Code int `json:"code"`
Message string `json:"message"`
}
func BadRequest(w http.ResponseWriter, msg string){
RespMessage(w, 400, msg)
}
func RespMessage(w http.ResponseWriter, code int, msg string){
w.WriteHeader(code)
json.NewEncoder(w).Encode(Message{Code:code, Message:msg})
}
func Post(path string, fn func(context.Context, http.ResponseWriter, *http.Request)) {
handle(POST, path, fn)
}
func Get(path string, fn func(context.Context, http.ResponseWriter, *http.Request)) {
handle(GET, path, fn)
}
func Put(path string, fn func(context.Context, http.ResponseWriter, *http.Request)) {
handle(PUT, path, fn)
}
func Delete(path string, fn func(context.Context, http.ResponseWriter, *http.Request)) {
handle(DELETE, path, fn)
}
func handle(method Method, path string, fn func(context.Context, http.ResponseWriter, *http.Request)) {
http.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
ctx := logging.NewContext()
logger := log.NewLogger(ctx)
found := r.Method == string(method)
logger.Debugf("method=%s, path=%s, found=%t", r.Method, r.URL.Path, found)
if found {
fn(ctx, w, r)
} else {
http.NotFound(w, r)
}
})
}
package main
import (
_ "controller"
"net/http"
"fmt"
"context"
)
func main(){
http.ListenAndServe(":3131", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment