Instantly share code, notes, and snippets.

@juanpabloaj /main.go
Last active Sep 22, 2018

Embed
What would you like to do?
HandlerFunc Generator
package main
import (
"errors"
"fmt"
"log"
"math/rand"
"net/http"
)
type Scope struct {
id int64
}
func (s *Scope) Log(format string, args ...interface{}) {
argsWithPrefix := make([]interface{}, 0, len(args)+1)
argsWithPrefix = append(argsWithPrefix, s.id)
argsWithPrefix = append(argsWithPrefix, args...)
log.Printf("%x "+format, argsWithPrefix...)
}
func (s *Scope) Hello(w http.ResponseWriter, r *http.Request) {
s.Log("%v %v %v", "in Hello function", "second argument", 1000)
s.Bye()
fmt.Fprintln(w, s.id, "hello world")
}
func (s *Scope) Bye() {
s.Log("in Bye funcion")
s.Log("%#v %#v", errors.New("some error"), s)
}
func HandlerFuncGenerator() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
s := Scope{
id: rand.Int63(),
}
s.Hello(w, r)
}
}
func main() {
http.HandleFunc("/", HandlerFuncGenerator())
log.Println("listening ...")
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment