Created
May 16, 2018 19:16
-
-
Save peterhellberg/e36274f213f7a2e2b89a3d837fbafbe1 to your computer and use it in GitHub Desktop.
A pretty minimal HTTP server example in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"io/ioutil" | |
"log" | |
"net/http" | |
"os" | |
"time" | |
) | |
func main() { | |
logger := log.New(os.Stdout, "", 0) | |
hs := setup(logger) | |
logger.Printf("Listening on http://0.0.0.0%s\n", hs.Addr) | |
hs.ListenAndServe() | |
} | |
func setup(logger *log.Logger) *http.Server { | |
return &http.Server{ | |
Addr: getAddr(), | |
Handler: newServer(logWith(logger)), | |
ReadTimeout: 5 * time.Second, | |
WriteTimeout: 10 * time.Second, | |
IdleTimeout: 60 * time.Second, | |
} | |
} | |
func getAddr() string { | |
if port := os.Getenv("PORT"); port != "" { | |
return ":" + port | |
} | |
return ":8383" | |
} | |
func newServer(options ...Option) *Server { | |
s := &Server{logger: log.New(ioutil.Discard, "", 0)} | |
for _, o := range options { | |
o(s) | |
} | |
s.mux = http.NewServeMux() | |
s.mux.HandleFunc("/", s.index) | |
return s | |
} | |
type Option func(*Server) | |
func logWith(logger *log.Logger) Option { | |
return func(s *Server) { | |
s.logger = logger | |
} | |
} | |
type Server struct { | |
mux *http.ServeMux | |
logger *log.Logger | |
} | |
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
if r.Method != "GET" { | |
w.WriteHeader(http.StatusMethodNotAllowed) | |
return | |
} | |
s.log("%s %s", r.Method, r.URL.Path) | |
s.mux.ServeHTTP(w, r) | |
} | |
func (s *Server) log(format string, v ...interface{}) { | |
s.logger.Printf(format+"\n", v...) | |
} | |
func (s *Server) index(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte("Hello, world!")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Relying on the Enhanced routing patterns in 1.22
(
h.mux.HandleFunc("GET /users/{id}", h.user)
,r.PathValue("id")
, etc.)Playground https://go.dev/play/p/Rh2remscvb8