Skip to content

Instantly share code, notes, and snippets.

@maderaka
Last active October 12, 2015 19:02
Show Gist options
  • Save maderaka/58ebe2e92d390c5148cf to your computer and use it in GitHub Desktop.
Save maderaka/58ebe2e92d390c5148cf to your computer and use it in GitHub Desktop.
Web server sederhana dengan golang
package main
import (
"fmt"
"net/http"
)
var routes map[string]func(http.ResponseWriter, *http.Request)
func main() {
routes = make(map[string]func(http.ResponseWriter, *http.Request))
routes["/hello"] = hello
routes["/"] = home
server := http.Server{
Addr: ":8080",
Handler: &httpHandler{},
}
server.ListenAndServe()
}
// Home endpoint
func home(rw http.ResponseWriter, req *http.Request) {
fmt.Fprint(rw, "Home")
}
// Say hello endpoint
func hello(rw http.ResponseWriter, req *http.Request) {
fmt.Fprint(rw, "Hello World")
}
// HTTP Handler
type httpHandler struct{}
// Handling http request
func (handler *httpHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if endpoint, ok := routes[req.URL.String()]; ok {
endpoint(rw, req)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment