Created
May 7, 2016 20:12
-
-
Save martinlindhe/8db82905c236963673af41efbcc4697c to your computer and use it in GitHub Desktop.
Golang http server example
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" | |
"log" | |
"net/http" | |
"os" | |
"time" | |
) | |
var ( | |
httpPort = "8080" | |
listenIP = "localhost" | |
) | |
func main() { | |
server := pastebin.NewHttpServer(listenIP, httpPort) | |
server.Serve() | |
} | |
type Server struct { | |
ListenHost string | |
ListenPort string | |
Logger *log.Logger | |
} | |
func NewHttpServer(listenIP, httpPort string) *Server { | |
res := Server{ | |
ListenHost: listenIP, | |
ListenPort: httpPort, | |
Logger: log.New(os.Stdout, "server> ", log.Ltime|log.Lshortfile)} | |
http.HandleFunc("/", res.HandleIndex) | |
return &res | |
} | |
func (s *Server) Serve() { | |
listenString := s.ListenHost + ":" + s.ListenPort | |
s.Logger.Println("Serving http://" + listenString) | |
s.Logger.Fatal(http.ListenAndServe(listenString, nil)) | |
} | |
func (s *Server) HandleIndex(w http.ResponseWriter, r *http.Request) { | |
defer timeTrack(time.Now(), w, "HandleIndex") | |
s.httpHeaders(w) | |
io.WriteString(w, "hello, world<br/><br/>") | |
} | |
func (s *Server) httpHeaders(w http.ResponseWriter) { | |
w.Header().Set("Content-Type", "text/html; charset=UTF-8") | |
} | |
func timeTrack(start time.Time, w http.ResponseWriter, name string) { | |
elapsed := time.Since(start) | |
io.WriteString(w, "<footer>"+name+" generated in "+elapsed.String()+"</footer>") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
undefined: pastebin in pastebin.NewHttpServer
- Line 19