Skip to content
Thanatat Tamtan edited this page Sep 23, 2023 · 4 revisions

Since hime use net/http handler, you can use net/http middleware style, or any middleware library that work with net/http.

package main

import (
	"log"
	"net/http"

	"github.com/moonrhythm/hime"
)

func main() {
	app := hime.New()

	h := logRequest(hime.Handler(index))

	app.Handler(h)
	app.Address(":8080")
	err := app.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}

func index(ctx *hime.Context) error {
	return ctx.String("Hello, Hime!!!")
}

func logRequest(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Printf("[%s] %s\n", r.Method, r.RequestURI)
		h.ServeHTTP(w, r)
	})
}

Using hime handler inside middleware

func logRequest(h http.Handler) http.Handler {
	return hime.Handler(func(ctx *hime.Context) error {
		log.Printf("[%s] %s\n", ctx.Method, ctx.RequestURI)
		return ctx.Handle(h)
	})
}

Using parapet inside hime's app

package main

import (
	"log"
	"net/http"

	"github.com/moonrhythm/hime"
)

func main() {
	app := hime.New()

	app.Server().UseFunc(panicRecovery)
	app.Server().UseFunc(logRequest)

	app.Handler(hime.Handler(index))
	app.Address(":8080")
	err := app.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}

func index(ctx *hime.Context) error {
	panic("oh no!!!")
}

func panicRecovery(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			err := recover()
			if err != nil {
				log.Println(err)
				http.Error(w, "Something went wrong D:", http.StatusInternalServerError)
			}
		}()
		h.ServeHTTP(w, r)
	})
}

func logRequest(h http.Handler) http.Handler {
	return hime.Handler(func(ctx *hime.Context) error {
		log.Printf("[%s] %s\n", ctx.Method, ctx.RequestURI)
		return ctx.Handle(h)
	})
}
h := alice.New(
	panicRecovery,
	logRequest,
).Then(hime.Handler(index))

Clone this wiki locally