Last active
October 12, 2015 19:02
-
-
Save maderaka/58ebe2e92d390c5148cf to your computer and use it in GitHub Desktop.
Web server sederhana dengan golang
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 ( | |
"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