Skip to content

Instantly share code, notes, and snippets.

@KentaKudo
Last active February 14, 2019 14:21
Show Gist options
  • Save KentaKudo/539c052f5d889f84f7174fc3c82aeb30 to your computer and use it in GitHub Desktop.
Save KentaKudo/539c052f5d889f84f7174fc3c82aeb30 to your computer and use it in GitHub Desktop.
A rough idea of a web app framework in Go
package webapp
import (
"fmt"
"net/http"
)
type Error struct {
code int
}
func (e Error) Error() string { return "" }
func fail(w http.ResponseWriter, err Error) {}
type HandlerFunc func(http.ResponseWriter, *http.Request) error
func (fn HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := fn(w, r); err != nil {
if ierr, ok := err.(Error); ok {
fail(w, ierr)
} else {
e := Error{code: http.StatusInternalServerError}
fail(w, e)
}
}
}
func get(fn HandlerFunc) HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
if r.Method != "GET" {
return fmt.Errorf("NotFound")
}
return fn(w, r)
}
}
func sayhello(w http.ResponseWriter, r *http.Request) error {
fmt.Fprintln(w, "Hi!")
return nil
}
func main() {
mux := http.NewServeMux()
mux.Handle("/hello", get(sayhello))
http.ListenAndServe(":8080", mux)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment