Skip to content

Instantly share code, notes, and snippets.

@swizzley
Last active January 25, 2022 15:38
Show Gist options
  • Save swizzley/6a83ea78968f68c6141f7690cee9e184 to your computer and use it in GitHub Desktop.
Save swizzley/6a83ea78968f68c6141f7690cee9e184 to your computer and use it in GitHub Desktop.
go http server
import (
"os"
"encoding/json"
"log"
"html/template"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
var (
rtr *mux.Router
tmpl *template.Template
)
func main() {
tmpl, err = template.ParseGlob("html/templates/*")
if err != nil {
log.Fatal(err)
}
rtr = mux.NewRouter()
rtr.PathPrefix("/js/").Handler(http.StripPrefix("/js/", http.FileServer(http.Dir("html/js"))))
rtr.PathPrefix("/css/").Handler(http.StripPrefix("/css/", http.FileServer(http.Dir("html/css"))))
rtr.PathPrefix("/images/").Handler(http.StripPrefix("/images/", http.FileServer(http.Dir("data/images"))))
rtr.HandleFunc("/health", health)
rtr.HandleFunc("/", index).Methods("GET")
//****************** MUST BE END OF MAIN ******************\\
s := &http.Server{
Addr: ":8080",
Handler: handlers.LoggingHandler(io.MultiWriter(os.Stdout), rtr),
MaxHeaderBytes: 1 << 62,
}
err := s.ListenAndServe()
if err != nil {
log.Fatal("server failed", err)
}
//****************** MUST BE END OF MAIN ******************\\
}
func health(w http.ResponseWriter, r *http.Request) {
status := struct {
Status string
}{
"OK",
}
w.Header().Set("Content-Type", "application/json")
j, _ := json.Marshal(status)
w.Write(j)
}
func index(w http.ResponseWriter, r *http.Request) {
tmpl.ExecuteTemplate(w, "index.html", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment